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

vlurs2pr  于 12个月前  发布在  Ruby
关注(0)|答案(4)|浏览(119)

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

class ExampleClass
  def example_method    
  end
  example_method
end

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

class ExampleClass
  def example_method
  end
end

def example_method1
end

example_method1

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

6ju8rftf

6ju8rftf1#

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

class ExampleClass
  def self.class_method
    puts "I'm a class method"
  end
  class_method
end

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

gg58donl

gg58donl2#

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

p self.class # => Object
p self.private_methods.sort # => [:Array, :Complex, ... :using, :warn] # all (?) from Kernel module

def aaaa
end

p self.private_methods.sort # => [:aaaa, :Array,  ... :using, :warn]
mwg9r5ms

mwg9r5ms3#

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

uujelgoq

uujelgoq4#

我将试着解释如下。

class MyClass
  def self.my_method
    puts "Me, I'm a class method. Note that self = #{self}"  
  end

  def my_method
    puts "Me, I'm an instance method. Note that self = #{self}"
  end

  # I'm about to invoke :my_method on self. Which one will it be?"
  # "That depends on what self is now, of course.

  puts "self = #{self}"

  # OK. It's MyClass. But wait. I'm just defining the set now.
  # Do the methods I defined above even exist yet?
  # Does the class exist yet? Let's find out.

  print "class methods: "
  puts self.methods(false)
  print "instance methods: "
  puts self.instance_methods(false)
# Cool! Let's try invoking my_method

  my_method

  # It worked. It was the class method because self = MyClass

  # Now let's see if we can create an instance of the class before
  # we finish defining the class. Surely we can't.

  my_instance = new
  puts "my_instance = #{my_instance}"

  # We can! Now that's very interesting. Can we invoke the
  # instance method on that instance?

  my_instance.my_method

  # Yes!
end

定义类时打印以下内容:

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

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

MyClass.my_method
  #-> Me, I'm a class method. Note that self = MyClass
my_instance = MyClass.new
my_instance.my_method
  #-> Me, I'm an instance method. Note that self = #<MyClass:0x007fd61181d668>

相关问题