Aru*_*hit 3 ruby singleton-methods ruby-1.9.3
来自 Doc of define_singleton_method
我有两种语法来定义singleton方法如下:
define_singleton_method(symbol){block} - > proc:
使用上面的语法,我尝试了下面的代码和我理解的语法:
define_singleton_method :foo do |params = {}|
params
end
#=> #<Proc:0x20e6b48@(irb):1 (lambda)>
foo
#=> {}
foo(bar: :baz)
#=> {:bar=>:baz}
foo(bar: :baz ,rar: :gaz )
#=> {:bar=>:baz, :rar=>:gaz}
Run Code Online (Sandbox Code Playgroud)
但需要有人的帮助,用以下语法找出每个例子.
define_singleton_method(symbol,method) - > new_method
根据文档 - 方法参数可以是a Proc,a Method或UnboundMethod对象.我没有在那里得到任何例子.
谁能帮助我在这里得到一个反对斜体字的例子?
甲Proc目的是通过使用创建的lambda,proc,->,Proc.new或&在参数列表语法.甲Method对象可以通过使用获得method方法和UnboundMethod可以通过使用获得instance_method方法.以下是每个例子:
p = Proc.new {|x| puts x}
m = method(:puts)
um = Object.instance_method(:puts)
define_singleton_method(:my_puts1, p)
define_singleton_method(:my_puts2, m)
define_singleton_method(:my_puts3, um)
my_puts1 42
my_puts2 42
my_puts3 42
Run Code Online (Sandbox Code Playgroud)
与Proc:
define_singleton_method(:foo, proc{ 'foo' })
foo #=> 'foo'
Run Code Online (Sandbox Code Playgroud)
与Method:
oof = 'oof'
oof.define_singleton_method(:foo, oof.method(:reverse))
oof.foo #=> "foo"
Run Code Online (Sandbox Code Playgroud)
与UnboundMethod:
oof = 'oof'
oof.define_singleton_method(:foo, String.instance_method(:reverse))
oof.foo #=> "foo"
Run Code Online (Sandbox Code Playgroud)