Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
like image 665
Ramy Avatar asked Oct 17 '11 00:10

Ramy


People also ask

How do you find the method of an object?

The first method to find the methods is to use the dir() function. This function takes an object as an argument and returns a list of attributes and methods of that object. From the output, we can observe that it has returned all of the methods of the object.

Are methods in Ruby objects?

In Ruby, methods are not objects.

Does Ruby have class methods?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.

How do I find the class of an object in Ruby?

Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false .


1 Answers

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.

like image 131
Candide Avatar answered Sep 21 '22 15:09

Candide