I read through the ruby docs examples but I’m still not sure what is happening in this code:
sentence = "How are you?"
sentence.chars.reduce do |memo, char|
%w[a e i o u y].include?(char) ? memo + char * 5 : memo + char
end
What is the memo when the block of code is first executed? What do the subsequent 5 steps look like?
Since you didn’t provide a default value for
reduce, it will setmemoto be the first value insentence.chars, which is"H".Iteration #1:
memois"H"charis"o""Hooooo"The result of the first iteration is then passed into the block as the first argument. So in iteration #2:
memois"Hooooo"charis"w""Hooooow"This will continue for each element of the array and the end result will be the result of the block after it is applied to the last element.
A trivial way to see this in action is just executing the following code: