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?
I experimented with methods()
method and got such results:
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
#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
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
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With