简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM