Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the `Object#define_singleton_method(symbol, method)` works in ruby?

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?

like image 328
Arup Rakshit Avatar asked Dec 06 '22 08:12

Arup Rakshit


2 Answers

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
like image 86
sepp2k Avatar answered Apr 27 '23 00:04

sepp2k


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"
like image 26
mdesantis Avatar answered Apr 27 '23 00:04

mdesantis