[英]How to define instance method in ruby dynamically?
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行写什么?
use define_method
like 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"
define_method 'fizz' do
puts 'fizz'
end
...or accepting a block ......或接受一个街区
define_method 'fizz', &block
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.