Ramy
Ramy

Reputation: 21261

get methods of an object in ruby

I'm a little confused about this behavior from the ruby (1.9) interpreter

 class Foo
   def pub
     private_thing
   end

   private
   def private_thing
     puts "private touch"
   end
 end



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

so far so good.

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

still ok. that's what I expected

but why is this empty?

x.methods(false)
=> []

while this gives me what I was expecting?

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

Upvotes: 12

Views: 20761

Answers (2)

Roland Mai
Roland Mai

Reputation: 31077

Indeed, the "methods" method seems to have disappeared. You should use public_instance_methods instead.

To explain why that x.methods(false) is behaving that way, look back at ruby 1.9.1 docs http://www.ruby-doc.org/core-1.9.1/Object.html#method-i-methods. If you see the source code if you pass in a parameter it behaves as singleton_methods, which is what you're seing.

Upvotes: 7

Mark Bolusmjak
Mark Bolusmjak

Reputation: 24399

It seems there is no documentation for Object#methods beyond ruby 1.9.1. As if it no longer exists. (take a look http://www.ruby-doc.org/core-1.9.3/Object.html)

I suppose this is to clarify that one should be using one of .singleton_methods or .instance_methods to determine where methods live.

In any case, an undocumented method can do whatever it likes.

Upvotes: 1

Related Questions