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