1. So I'm guessing that memo will start off with the value cat seeing as inject has no argument passed to it.
Documentation says:
If you do not explicitly specify an initial value for memo, then the
first element of collection is used as the initial value of memo.
2. I'm also guessing that the first word will then be sheep..then next word, bear.
You can use puts
to inspect each stage bar the final assignment, but that's just the return value of the inject method:
longest = %w{ cat sheep bear }.inject do |memo, word|
puts "memo is currently #{memo}",
"word is currently #{word}",
"-----------------------"
memo.length > word.length ? memo : word
end
#memo is currently cat
#word is currently sheep
#-----------------------
#memo is currently sheep
#word is currently bear
#-----------------------
longest #=> "sheep"
Another way
Finally another more Rubyish way to get the longest word:
%w{ cat sheep bear }.max_by(&:length) #=> "sheep"