Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby methods() method

Tags:

ruby

I want to understand how Ruby method methods() work.
I tried to Google with "ruby methods" but it's not what i need.
Also i've seen ruby-doc.org, but i didn't find this method.

Can you expain me how it works in details or give me a link?

Update

I experimented with methods() method and got such results:

'lab rat' code

class First
  def first_instance_mymethod
  end
  def self.first_class_mymethod
  end
end
class Second < First
  def second_instance_mymethod
  end
  def self.second_class_mymethod
  end
end

Work with Classes

#returns available methods list for class and ancestors
puts Second.methods.grep(/mymethod/)
  # => second_class_mymethod
  # => first_class_mymethod

#returns Class methods list for current class only 
puts Second.methods(false)
  # => second_class_mymethod

Work with Objects

obj = Second.new
def obj.obj_singleton_mymethod
end

#returns available methods list for object and ancestors
puts obj.methods.grep(/mymethod/)
  # => second_instance_mymethod
  # => first_instance_mymethod

#returns current object class methods
puts obj.methods(false)
  # => obj_singleton_mymethod
like image 272
Vladimir Tsukanov Avatar asked Jul 20 '11 12:07

Vladimir Tsukanov


2 Answers

The accepted answer misses a slight point. A fuller answer was given in the comment by keymone - .methods returns an array of symbols being names of all the methods defined on the given instance. For example:

irb(main):012:0> object = ""
=> ""
irb(main):013:0> object.instance_eval("def foo;:bar;end")
=> nil
irb(main):014:0> object.methods.include?(:foo)
=> true
irb(main):016:0> "".methods.include?(:foo)
=> false
like image 162
Paweł Obrok Avatar answered Oct 17 '22 17:10

Paweł Obrok


I'm not entirely sure why it's not in the ruby 1.9 docs (it seems to still be in the code), but you can see the documentation in the 1.8.7 docs: http://www.ruby-doc.org/core-1.8.7/classes/Object.html#M000032

Basically, in ruby 1.9 it just returns a list of the symbols (names) for all the methods in a given class and its ancestors. (ruby 1.8 it returned a list of strings)

like image 26
SoftArtisans Avatar answered Oct 17 '22 17:10

SoftArtisans