R
Russ McBride
map requires a block, right? So this works:
words = %w(ardvark anteater llama)
arr = words.map { |x| x + "!" }
arr #--> [ardvark!, anteater!, llama!]
But this doesn't:
arr2 = words.map lambda{ |x| x + "!"} #--> ArgumentError:
wrong number of arguments (1 for 0)
We can trigger a call to some object's to_proc method with the
ampersand. For example, this
will trigger the symbol's to_proc method, assuming there is one:
upcase_words = words.map(&:upcase)
and if we have already have this:
class Symbol
def to_proc
lambda{ |x| x.send(self) }
end
end
then we get:
#--> [ARDVARK, ANTEATER, LLAMA]
But, the to_proc method here is returning a Proc, not a block! So why
does this work?
As far as I can tell, the ampersand must be doing 2 things:
1- triggering the call to to_proc
2- converting the returned Proc object into a block for map to handle.
Is this right?
words = %w(ardvark anteater llama)
arr = words.map { |x| x + "!" }
arr #--> [ardvark!, anteater!, llama!]
But this doesn't:
arr2 = words.map lambda{ |x| x + "!"} #--> ArgumentError:
wrong number of arguments (1 for 0)
We can trigger a call to some object's to_proc method with the
ampersand. For example, this
will trigger the symbol's to_proc method, assuming there is one:
upcase_words = words.map(&:upcase)
and if we have already have this:
class Symbol
def to_proc
lambda{ |x| x.send(self) }
end
end
then we get:
#--> [ARDVARK, ANTEATER, LLAMA]
But, the to_proc method here is returning a Proc, not a block! So why
does this work?
As far as I can tell, the ampersand must be doing 2 things:
1- triggering the call to to_proc
2- converting the returned Proc object into a block for map to handle.
Is this right?