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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11314377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:15:19  来源:igfitidea点击:

How to define instance method in ruby dynamically?

rubymetaprogramming

提问by Arnis Lapsa

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?

在第 3 行写什么?

回答by Patrick Oscity

use define_methodlike this:

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

output:

输出:

method undefined
"i like turtles"

回答by lebreeze

define_method 'fizz' do
  puts 'fizz'
end

...or accepting a block

...或接受一个块

define_method 'fizz', &block