I'm going through an online lesson, which usually has a very simple one line solution. A problem states that, given the following array:
["emperor", "joshua", "abraham", "norton"]
I must use #inject
to get a single string of all names joined together with a string, each name initial capped, like this:
"Emperor Joshua Abraham Norton"
While this could easily be done with #map
and #join
, this particular exercise requires the use of #inject only. I came up with something like this:
["emperor", "joshua", "abraham", "norton"].inject("") do |memo, word|
memo << word.capitalize << " "
end
which would give me:
"Emperor Joshua Abraham Norton "
where the whitespace at the end of the string doesn't pass as the correct solution.
- How do I achieve this without the whitespace at the end?
- Is this even the right way to use
#inject
, passing an empty string? - Am I making correct use of the
<<
to combine strings?