我正在研究 Ruby 并尝试实现method_missing
,但它不起作用。例如,我想在之后打印方法名称,find_
但是当我在 Book 实例上调用它时,ruby 会引发“未定义的方法'find_hello'”。
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