2012-02-23 52 views
1

下面是一个例子:哪里()在instance_eval的定义Ruby的存储方法

class MyClass 
end 

obj = MyClass.new 
obj.instance_eval do 
    def hello 
    "hello" 
    end 
end 

obj.hello 
# => "hello" 

obj.methods.grep "hello" 
# => ["hello"] 

MyClass.instance_methods.grep "hello" 
# => [] 

MyClass的的实例方法不包含“你好”的方法,所以我的问题是在哪里红宝石存储(在instance_eval的定义的方法)?

+0

第一次确定是否有错字? – lucapette 2012-02-23 22:49:05

回答

2

看看这个:

obj = MyClass.new 
def obj.hello 
    "hello" 
end 

obj.hello #=> "hello" 
obj.singleton_methods #=> [:hello] 
obj.methods.grep :hello #=> [:hello] 

obj.instance_eval do 
    def hello2 ; end 
end # 

obj.singleton_methods #=> [:hello, :hello2] 

正如你所看到的,而不是使用instance_eval你也可以直接在对象上定义一个方法。在这两种情况下,它们都会在对象的单例类(本征类)中出现,可以通过Ruby 1.9中的obj.singleton_class和Ruby 1.8中的class << self ; self; end惯用法访问。