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

Arn*_*psa 13 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"
Run Code Online (Sandbox Code Playgroud)

在第3行写什么?

Pat*_*ity 16

使用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
Run Code Online (Sandbox Code Playgroud)

输出:

method undefined
"i like turtles"
Run Code Online (Sandbox Code Playgroud)


leb*_*eze 10

define_method 'fizz' do
  puts 'fizz'
end
Run Code Online (Sandbox Code Playgroud)

......或接受一个街区

define_method 'fizz', &block
Run Code Online (Sandbox Code Playgroud)