Need some explnation to_proc

V

vishy

Hi,
I am looking for some explanation for this ruby snippet.
class Symbol
def to_proc
lambda {|x, *args| x.send(self, *args)}
end
end
words = %w(Jane, aara, multiko)
upcase_words = words.map(&:upcase)

What I understand is that,:upcase is a symbol,and by appending
&,to_proc is fired.What happens next? What is x and *args in to_proc ?
thanks
 
S

Sebastian Hungerecker

vishy said:
What is x and *args in to_proc ?

They're the arguments to the block:
If you words.map, map will basically do:
yield "Jane"
yield "aara"
yield "multiko"
Those will be the values for x on each iteration of the block. If you'd use a
method that yielded multiple values at once, the additional ones would go
into args. Example:
class Integer
def foo(other)
puts self+other
end
end
[1,5,3].each_with_index(&:foo), would do the following:
yield 1,0 # x = 1, args = [0]
yield 5,1 # x = 5, args = [1]
yield 3,2 # x = 3, args = [2]
which would result in the following method calls:
1.foo 0
5.foo 1
3.foo 2
and the following output:
1
6
5


HTH,
Sebastian
 

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,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top