![](/img/trans.png)
[英]Ruby: How do I get the methods of a class without having an object of it?
[英]get methods of an object in ruby
我對ruby(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"]
實際上,“方法”方法似乎已經消失了。 您應該使用public_instance_methods 。
要解釋為什么x.methods(false)
的行為方式,請回顧一下ruby 1.9.1 docs http://www.ruby-doc.org/core-1.9.1/Object.html#method-i-methods 。 如果你看到源代碼,如果你傳入一個參數,它表現為singleton_methods,這就是你所看到的。
似乎除了ruby 1.9.1之外沒有Object#方法的文檔。 好像它不再存在。 (看看http://www.ruby-doc.org/core-1.9.3/Object.html )
我想這是為了澄清一個人應該使用.singleton_methods或.instance_methods之一來確定方法的存在位置。
無論如何,未記錄的方法可以做任何它喜歡的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.