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)
或者,如果您想对对象进行猴子修补以使其变得容易
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 内联,这可能更具可读性
class << y
define_method(:bar, proc { "foobar!" })
end
或者,
class << y
define_method(:bar) { "foobar!" }
end
这是最易读的,但可能不符合您的需要
def y.bar
"goodbye"
end
This question is highly related