在Ruby中调用Class中的示例方法

vlurs2pr  于 2023-10-17  发布在  Ruby
关注(0)|答案(4)|浏览(156)

我对此感到非常困惑。在《Programming Ruby》一书中,它说,“接收者检查自己类中的方法定义”。
所以类对象存储所有的示例方法。那为什么我不能在类中调用示例方法呢?
举例来说:

  1. class ExampleClass
  2. def example_method
  3. end
  4. example_method
  5. end

我不能在ExampleClass中调用example_method。
但是,如果我在顶层定义一个方法,像这样:

  1. class ExampleClass
  2. def example_method
  3. end
  4. end
  5. def example_method1
  6. end
  7. example_method1

然后我可以调用顶级方法example_method1。
顶级不也是一个职业吗?为什么它与ExampleClass中的调用示例方法不同?

6ju8rftf

6ju8rftf1#

你不能以你写的方式调用这个函数的最大原因是,正如你所说,它是一个示例方法。
试着这样定义它:

  1. class ExampleClass
  2. def self.class_method
  3. puts "I'm a class method"
  4. end
  5. class_method
  6. end

我相信你会发现你有一个不同的结果。这不是说它是“顶级”,这是它是否在你正在处理的范围。因为你处理的是一个类,所以类方法是必要的。如果你正在处理一个对象(一个示例化的类),它是一个不同的“作用域”。

gg58donl

gg58donl2#

这些“全局”方法是一个例外。它们被定义为Object的私有示例方法。一切都继承自Object,所以这些方法是“全局”可见的。

  1. p self.class # => Object
  2. p self.private_methods.sort # => [:Array, :Complex, ... :using, :warn] # all (?) from Kernel module
  3. def aaaa
  4. end
  5. p self.private_methods.sort # => [:aaaa, :Array, ... :using, :warn]
mwg9r5ms

mwg9r5ms3#

接收方检查自己类中的方法定义。接收器是ExampleClassExampleClass的类是Class。在Class类中没有example_method方法,因此,你得到了一个NoMethodError

uujelgoq

uujelgoq4#

我将试着解释如下。

  1. class MyClass
  2. def self.my_method
  3. puts "Me, I'm a class method. Note that self = #{self}"
  4. end
  5. def my_method
  6. puts "Me, I'm an instance method. Note that self = #{self}"
  7. end
  8. # I'm about to invoke :my_method on self. Which one will it be?"
  9. # "That depends on what self is now, of course.
  10. puts "self = #{self}"
  11. # OK. It's MyClass. But wait. I'm just defining the set now.
  12. # Do the methods I defined above even exist yet?
  13. # Does the class exist yet? Let's find out.
  14. print "class methods: "
  15. puts self.methods(false)
  16. print "instance methods: "
  17. puts self.instance_methods(false)
  1. # Cool! Let's try invoking my_method
  2. my_method
  3. # It worked. It was the class method because self = MyClass
  4. # Now let's see if we can create an instance of the class before
  5. # we finish defining the class. Surely we can't.
  6. my_instance = new
  7. puts "my_instance = #{my_instance}"
  8. # We can! Now that's very interesting. Can we invoke the
  9. # instance method on that instance?
  10. my_instance.my_method
  11. # Yes!
  12. end

定义类时打印以下内容:

  1. self = MyClass
  2. class methods: my_method
  3. instance methods: my_method
  4. Me, I'm a class method. Note that self = MyClass
  5. my_instance = #<MyClass:0x007fd6119125a0>
  6. Me, I'm an instance method. Note that self = #<MyClass:0x007fd6119125a0>

现在让我们确认这些方法可以从类外部调用。这里不应该有任何惊喜:

  1. MyClass.my_method
  2. #-> Me, I'm a class method. Note that self = MyClass
  3. my_instance = MyClass.new
  4. my_instance.my_method
  5. #-> Me, I'm an instance method. Note that self = #<MyClass:0x007fd61181d668>
展开查看全部

相关问题