2011-10-17 149 views
12

对象的方法,我有点困惑从红宝石(1.9)解释得到红宝石

class Foo 
    def pub 
    private_thing 
    end 

    private 
    def private_thing 
    puts "private touch" 
    end 
end 



x = Foo.new 
x.pub 
private touch 
=> nil 

到目前为止好这种行为。

x.private_thing 
NoMethodError: private method `private_thing' called for #<Foo:0xb76abd34> 
from (irb):25 
from :0 

还行。这就是我所期望的

但为什么这是空的?

x.methods(false) 
=> [] 

虽然这给了我所期待的?

Foo.instance_methods(false) 
=> ["pub"] 

回答

1

看来除了ruby 1.9.1之外,没有关于Object#方法的文档。就好像它不再存在一样。 (看看http://www.ruby-doc.org/core-1.9.3/Object.html

我想这是澄清,应该使用.singleton_methods或.instance_methods之一来确定方法的生活方式。

在任何情况下,无证方法都可以做任何喜欢的事情。