Yossef Mendelssohn
6/27/2008 6:59:00 PM
On Jun 27, 1:17 pm, Ruby Freak <twscann...@gmail.com> wrote:
> words = %w(Jane, aara, multiko)
> upcase_words = words.map(&:upcase)
>
> So we are overriding the to_proc method with
> lambda {|x, *args| x.send(self, *args)}
>
> so in the lambda, the x in |x, args| is the same as the |x| in the
> block (Jane, aara, multiko)(yes?, no?)
Yes
> and the args in |x, args| is the symbol :ucase, (yes?, no?)
No
> I don't understand x.send(self, *args)
> self is the symbol :ucase ?
> but so is args ???
>
> In my brain, at some point I get "jane.send(self, *args)"
>
> I'm lost.
So you know that & is a shorthand for saying "this is a block" and it
converts the following value using its to_proc method, right? That's
where the convenient shorthand of &:upcase comes from. Look at these
snippets:
%w[one two three].collect { |x| x.upcase }
%w[one two three].collect { |x| x.send(:upcase) } # same as above
class Symbol
def to_proc
lambda { |x| x.send(self) }
end
end
%w[one two three].collect(&:upcase) # calls :upcase.to_proc
:upcase.to_proc returns lambda { |x| x.send(:upcase) }
I don't quite understand when I see the definition of Symbol#to_proc
with *args. Where might these args come from? Maybe I'm just not using
Symbol#to_proc correctly.
Try this on for size:
class Symbol
def to_proc
lambda do |x, *args|
p x
p self
p args
x.send(self, *args)
end
end
end
%w[one two three].collect(&:upcase)
(output)
"one"
:upcase
[]
"two"
:upcase
[]
"three"
:upcase
[]
=> ["ONE", "TWO", "THREE"]
Hope this helped.
--
-yossef