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

时间:2015-03-30 20:51:08

标签: 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中的调用实例方法?

4 个答案:

答案 0 :(得分:4)

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

尝试以这种方式定义它:

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

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

答案 1 :(得分:2)

那些"全球"方法是个例外。它们被定义为Object的私有实例方法。一切都继承自Object,因此这些方法是全球性的#34;可见。

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]

答案 2 :(得分:2)

我会尝试解释如下。

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>

答案 3 :(得分:2)

接收方在自己的类中检查方法定义。接收者是ExampleClassExampleClass的班级为Classexample_method课程中没有Class方法,因此,您获得了NoMethodError

相关问题