From the Doc of define_singleton_method
I got two syntax to define the singleton
method as below :
define_singleton_method(symbol) { block } -> proc :
With the above syntax I tried the below code and the syntax I understood:
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}
But need someone's help to figure out one example of each with the below syntax.
define_singleton_method(symbol, method) -> new_method
as per the doc - The method parameter can be a Proc
, a Method
or an UnboundMethod
object. I didn't get any examples there.
Can anyone help me here to get one example of against the italic words?
A Proc
object is created by using lambda
, proc
, ->
, Proc.new
or the &
syntax in a parameter list. A Method
object can be obtained by using the method
method and an UnboundMethod
can be obtained by using the instance_method
method. So here are examples of each of these:
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
With a Proc
:
define_singleton_method(:foo, proc{ 'foo' })
foo #=> 'foo'
With a Method
:
oof = 'oof'
oof.define_singleton_method(:foo, oof.method(:reverse))
oof.foo #=> "foo"
With an UnboundMethod
:
oof = 'oof'
oof.define_singleton_method(:foo, String.instance_method(:reverse))
oof.foo #=> "foo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With