14

我想通过父类的类方法动态创建子类的实例方法。

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"

在第 3 行写什么?

4

2 回答 2

20

像这样使用define_method

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

输出:

method undefined
"i like turtles"
于 2012-07-03T15:43:03.530 回答
11
define_method 'fizz' do
  puts 'fizz'
end

...或接受一个块

define_method 'fizz', &block
于 2012-07-03T15:38:51.567 回答