繁体   English   中英

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

[英]Calling instance method in Class in Ruby

我对此非常困惑。 在编程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中的调用实例方法不同?

你不能以你编写的方式调用该函数的最大原因是,正如你所说的那样,它是一个实例方法。

尝试以这种方式定义它:

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

我相信你会发现你有不同的结果。 这并不是它的“顶级”,而是它是否适合您所处理的范围。 由于您正在处理类,因此需要使用类方法。 如果你正在处理一个对象(一个实例化的类),它就是一个不同的“范围”。

那些“全球”方法是个例外。 它们被定义为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]

我将尝试解释如下。

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>

接收器在其自己的类中检查方法定义。 接收器是ExampleClass ExampleClassClassClass Class类中没有example_method方法,你会得到一个NoMethodError

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM