本文介绍了在带有lambda的单个实例上重新定义单个ruby方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby中,有没有一种方法可以使用proc重新定义类的特定实例的方法?例如:
In Ruby, is there a way to redefine a method of a particular instance of a class using a proc? For example:
class Foo
def bar()
return "hello"
end
end
x = Foo.new
y = Foo.new
(类似):
y.method(:bar) = lambda { return "goodbye" }
x.bar
y.bar
制作:
hello
goodbye
谢谢.
推荐答案
def define_singleton_method_by_proc(obj, name, block)
metaclass = class << obj; self; end
metaclass.send(:define_method, name, block)
end
p = proc { "foobar!" }
define_singleton_method_by_proc(y, :bar, p)
或者,如果您想通过猴子修补对象来简化操作
or, if you want to monkey-patch Object to make it easy
class Object
# note that this method is already defined in Ruby 1.9
def define_singleton_method(name, callable = nil, &block)
block ||= callable
metaclass = class << self; self; end
metaclass.send(:define_method, name, block)
end
end
p = proc { "foobar!" }
y.define_singleton_method(:bar, p)
#or
y.define_singleton_method(:bar) do
"foobar!"
end
或者,如果您想内联定义proc,则可能更易读
or, if you want to define your proc inline, this may be more readable
class << y
define_method(:bar, proc { "foobar!" })
end
或
class << y
define_method(:bar) { "foobar!" }
end
这是最易读的内容,但可能不符合您的需求
this is the most readable, but probably doesn't fit your needs
def y.bar
"goodbye"
end
这篇关于在带有lambda的单个实例上重新定义单个ruby方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!