I am trying to get definition of method :foo from Class object.
class Bar
def foo(required_name, optional="something")
puts "Hello args are #{required_name}, #{optional}"
end
def self.bar
puts "I am easy, since I am static"
end
end
I cannot create instance of class since I need method definition to evaluate should I create object (app requirments). Bar.class.???(:foo)
I can get with bar
definition with Bar.class.method(:bar)
but of course I need foo
, thanks!
UPDATE:
Using Ruby 1.8.7
In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.
To call an object's method, you must use the object name and the dot (.) operator followed by the method name, for example object.
You can use the method instance_method
on a class like this :
Bar.instance_method(:foo)
which will return an instance of UnboundMethod
. (See http://ruby-doc.org/core-1.9.3/UnboundMethod.html)
You can discover if the class has an instance method :foo
like so:
Bar.instance_methods.include? :foo
An example:
String.instance_methods.include? :reverse
=> true
String.instance_methods.include? :each
=> false
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