編輯:我使用Ruby 2.0.0版本困惑於「respond_to?」方法
我有一個文件example.rb
def say_hello
puts 'hi'
end
puts respond_to?(:say_hello)
say_hello
當運行該代碼時,輸出以下代碼:
false
hi
我很困惑爲什麼false會返回「respond_to?」當我可以使用該方法時。
「respond_to?」方法似乎工作,雖然這樣說:
class Person
def say_bye
puts 'bye'
end
end
mike = Person.new
puts mike.respond_to?(:say_bye)
mike.say_bye
輸出是:「respond_to代碼」
true
bye
沒有人有任何見解,爲什麼在第一種情況下返回false?
有趣,我剛?在irb中運行它,它爲我工作。你是否試圖通過自我調用來更加明確? '把self.respond_to?(:say_hello)' – AdamT
self.respond_to(:say_hello)返回false。 – MichaelHajuddah
你運行的是哪個版本的Ruby? – Shoe