Ruby类方法。它是否被主要对象调用?

时间:2016-08-10 01:45:20

标签: ruby

我有一个看起来像这样的课程:

class Test
  def self.hello
    puts "I say hello"
  end

  def goodbye
    puts 'goodbye'
  end

  hello
  goodbye
end

这是我的输出:

 ruby class_methods.rb
I say hello
class_methods.rb:11:in `<class:Test>': undefined local variable or method `goodbye' for Test:Class (NameError)
    from class_methods.rb:1:in `<main>'

什么是hello被召唤?它看起来确实被调用但它被调用的是什么?我认为它被称为主要对象......但为什么这有意义呢?我认为只能在类对象本身而不是main对象上调用类方法?

4 个答案:

答案 0 :(得分:3)

  

你好被召唤的是什么?

每当没有显式接收器时,接收器为self。所以这个电话是隐含的:

self.hello

...其中self是类Test,您刚刚定义了self.hello方法。

找不到

goodbye,因为它是在类Test的实例上定义的,而不是当前调用它的类本身。

答案 1 :(得分:2)

def self.hello是一种类方法

 def self.hello
    puts "I say hello"
  end

 hello or Test.hello
 #I say hello

def goodbyeTest

类的实例方法
  def goodbye
    puts 'goodbye'
  end

 Test.new.goodbye  #instance of Test
 #goodbye

答案 2 :(得分:0)

self定义类方法,而定义一个没有self的方法意味着该方法是一个实例方法,因此,调用goodbye会引发错误,因为没有接收者,一个实例发送该消息或调用该方法需要Test类。

当ruby解析类并评估代码时,它可以调用hello,因为不需要实例化对象。

答案 3 :(得分:0)

您将hello定义为类方法,而goodbye是一个实例方法。

class Test
  def self.hello
    puts "I say hello"
  end
  ...
end

这个类方法,因为你在self上调用hello,这是Test类,所以你可以通过Test.hello调用hello。

...
def goodbye
    puts 'goodbye'
end

要调用goodbye方法,因为这是一个实例方法,您需要使用Test.new方法创建Test实例。因此,您需要使用Test.new.goodbye来调用再见方法。

相关问题