Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby get instance method definition from Class

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

like image 746
Haris Krajina Avatar asked Aug 21 '12 13:08

Haris Krajina


People also ask

Can a class method call an instance method Ruby?

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.

How do you find the class method in Ruby?

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.

How do you call a method from an instance of a class?

To call an object's method, you must use the object name and the dot (.) operator followed by the method name, for example object.


2 Answers

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)

like image 65
tomferon Avatar answered Oct 05 '22 23:10

tomferon


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
like image 40
Ian Bishop Avatar answered Oct 06 '22 00:10

Ian Bishop