如何动态定义ruby中的实例方法?

时间:2012-07-03 15:35:14

标签: ruby metaprogramming

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

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行写什么?

2 个答案:

答案 0 :(得分:15)

像这样使用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"

答案 1 :(得分:9)

define_method 'fizz' do
  puts 'fizz'
end

......或接受一个块

define_method 'fizz', &block