How to define instance method in ruby dynamically?

metaprogramming, ruby

Solution

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"

Problem

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?

Original source