[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Need some explnation to_proc

vishy

3/3/2008 4:11:00 PM

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
1 Answer

Sebastian Hungerecker

3/3/2008 4:30:00 PM

0

vishy wrote:
> 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
--
Jabber: sepp2k@jabber.org
ICQ: 205544826