Defining a Ruby get instance method from a class

I am trying to get a method definition: foo from a 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 an instance of the class, since I need a method definition to evaluate whether I should create an object (application requirements). Bar.class.???(:foo)

I can define bar with Bar.class.method(:bar) , but of course I need foo , thanks!

UPDATE:

Using Ruby 1.8.7

+6
source share
2 answers

You can use the instance_method method for 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 )

+7
source

You can find out if the class has an instance method :foo like this:

 Bar.instance_methods.include? :foo 

Example:

 String.instance_methods.include? :reverse => true String.instance_methods.include? :each => false 
+1
source

Source: https://habr.com/ru/post/923391/


All Articles