questions re Method#to_proc

E

Eli Bendersky

Hello all,

Some things are unclear to me about Method#to_proc. I understand the
following:

plus = 12.method("+")
p plus.call(13) # prints 25

newplus = plus.unbind.bind(20)
p newplus.call(13) # prints 33

Although the usefulness of this eludes me :)

However, this:

plus_proc = plus.to_proc
p plus_proc.call(10) # prints 10

Is unclear... How does it work ? What does it mean for a Proc to be
bound to an object ? Can someone provide an example where it is useful
?

Also, have the 'bind' and 'unbind' methods of Method / UnboundMethod
anything in common with Proc#binding or the Binding class ? Have
Proc#binding and the Binding class anything in common ? How about
Kernel#binding ?

Thanks,
Eli
 
E

Eli Bendersky

Eli said:
Hello all,

Some things are unclear to me about Method#to_proc. I understand the
following:

plus = 12.method("+")
p plus.call(13) # prints 25

newplus = plus.unbind.bind(20)
p newplus.call(13) # prints 33

Although the usefulness of this eludes me :)

However, this:

plus_proc = plus.to_proc
p plus_proc.call(10) # prints 10

Is unclear... How does it work ? What does it mean for a Proc to be
bound to an object ? Can someone provide an example where it is useful
?

Also, have the 'bind' and 'unbind' methods of Method / UnboundMethod
anything in common with Proc#binding or the Binding class ? Have
Proc#binding and the Binding class anything in common ? How about
Kernel#binding ?

Has anyone insights on this topic ?

Additionally, the following, IMHO demostrates a very surprising and
unnatural behavior of to_proc:

def foo(arr)
puts "Got an array with #{arr.length} elements"
end

# works correctly
foo([4, 5, 6])

foo_proc = method:)foo).to_proc

# throws an ArgumentError: 3 for 1
foo_proc.call([4, 5, 6])

# works correctly
foo_proc.call([[4, 5, 6]])

The Proc created by to_proc is obviously different from the original
method, since it "folds" its arguments into an array. I guess there
will be even more problems when the method receives more than one array
as an argument.
How should this be handled correctly ?

Thanks
Eli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top