如果执行test1
等其他类中没有定义的方法,会走到method_missing
方法中来。
class Student
attr_accessor :name
attr_accessor :age
def initialize(name, age)
@name = name
@age = age
end
def method_missing(name, *args)
if name.to_s =~ /test1/
return "test1"
end
"a ghost method"
end
end
s1 = Student.new("lily", 25)
puts s1.name
s1.age
p s1.test1 #=> test1
p s1.test2 #=> "a ghost method"