17

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?

2 Answers 2

23

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"
Sign up to request clarification or add additional context in comments.

4 Comments

almost what I need. problem is - &block`s self should be instance of Bar. so it would be possible to write something like this: class Bar ; add_fizz_method do ; p self.bar_name ; end ; end
try p self.class below p 'i like turtles'. self already is an instance of Bar.
Btw: if you want to return nil instead of throwing a NoMethodError before having called add_fizz_method, you can declare an empty fizz method in the Foo class.
heh... I wrote define_method 'fizz', do &block.call end previously. tyvm. got what I needed and learned a thing.
11
define_method 'fizz' do
  puts 'fizz'
end

...or accepting a block

define_method 'fizz', &block

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.