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
這是mo ST可讀,但可能不適合您的需求
def y.bar
"goodbye"
end
This question is highly related
如果他在一個簡單變量中有一個外部定義的過程,很難將其引入由<< str1創建的新範圍,而不訴諸全局或實例變量 – 2009-04-29 20:13:39