我正在學習Ruby並嘗試實施method_missing
,但它不起作用。例如,我想在find_
之後打印方法名稱,但是當我在Book實例上調用它時,ruby引發了「未定義的方法'find_hello'」。即使在method_missing處理後未定義的方法
TEST_05.RB
module Searchable
def self.method_missing(m, *args)
method = m.to_s
if method.start_with?("find_")
attr = method[5..-1]
puts attr
else
super
end
end
end
class Book
include Searchable
BOOKS = []
attr_accessor :author, :title, :year
def initialize(name = "Undefined", author = "Undefined", year = 1970)
@name = name
@author = author
@year = year
end
end
book = Book.new
book.find_hello
非常感謝!現在它工作正常。 – 2013-03-24 06:35:11