Need help understanding Yield (trying to grasp Lambdas and Blocks)

Hi,

New to Ruby and currently trying to get a grasp of Lambdas and Blocks.
I’ve been able to understand basic uses of yield, I was stuck on this
problem in RubyMonk this problem in section 7.2, but finally came up
with the answer below. However, I must admit that I’m not sure if I’ve
fully grasped or explained adequately why the answer works, but I made
some comments on it.

Could someone review the code and offer some advice / help?

Thanks,

Emeka

Problem:

class Array
def transmogrify # see? no ‘fn’ parameter. magic.
result = []
each do |pair|
# how do you think ‘yield’ will be used here?
end
result
end
end

def names
[[“Christopher”, “Alexander”],
[“John”, “McCarthy”],
[“Joshua”, “Norton”]].transmogrify do |pair|
# by passing the entire element, we give more control to the block
end
end

My answer:

class Array
def transmogrify # define method transmogrify
result = [] # opens empty array called result
each do |pair| # calls block once for each element in object
result << yield(pair) # passes variable ‘pair’ to yield

returns modified block of code

pushes it to the array named ‘result’

end
result # calls up array named ‘result’
end
end

def names # define method called ‘names’
[[“Christopher”, “Alexander”],
[“John”, “McCarthy”],
[“Joshua”, “Norton”]].transmogrify do |pair| # calls method

transmogrify on given array

“#{pair[0]} #{pair[1]}” # passes elements in array through block of

code which takes each pair of elements in nested array and

combines into a single string

end
end

Hi,

Your descriptions are correct, but I find your terminology a bit
strange. For example, you describe “result = []” as “opening an empty
array namend result”. I’d rather call it “create an empty array and
assign it to the variable ‘result’”. Because “result” isn’t the name of
this specific array (that’s what you’d use a constant for), it’s a
generic reference which may point to any object at any time.

By the way, the “transmogrify” method is actually a reimplementation of
Enumerable#map:

Except that it forces you to pass a block (whereas Enumerable#map will
return an Enumerator if you don’t).