Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define instance method in ruby dynamically?

I want to dynamically create instance method of child class through class method of parent class.

class Foo
  def self.add_fizz_method &body
    # ??? (This is line 3)
  end
end

class Bar < Foo
end
Bar.new.fizz #=> nil

class Bar
  add_fizz_method do
    p "i like turtles"
  end
end
Bar.new.fizz #=> "i like turtles"

What to write on line #3?

like image 462
Arnis Lapsa Avatar asked Jul 03 '12 15:07

Arnis Lapsa


People also ask

How do you dynamically define a method in Ruby?

define_method is a method defined in Module class which you can use to create methods dynamically. To use define_method , you call it with the name of the new method and a block where the parameters of the block become the parameters of the new method.

How do you define an instance method?

Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.

What is MetaProgramming Ruby?

MetaProgramming gives Ruby the ability to open and modify classes, create methods on the fly and much more. A few examples of metaprogramming in Ruby are: Adding a new method to Ruby's native classes or to classes that have been declared beforehand. Using send to invoke a method by name programmatically.


2 Answers

use define_method like this:

class Foo
  def self.add_fizz_method &block
    define_method 'fizz', &block
  end
end

class Bar < Foo; end

begin
  Bar.new.fizz 
rescue NoMethodError
  puts 'method undefined'
end

Bar.add_fizz_method do
  p 'i like turtles'
end
Bar.new.fizz

output:

method undefined
"i like turtles"
like image 152
Patrick Oscity Avatar answered Oct 08 '22 18:10

Patrick Oscity


define_method 'fizz' do
  puts 'fizz'
end

...or accepting a block

define_method 'fizz', &block
like image 45
lebreeze Avatar answered Oct 08 '22 18:10

lebreeze