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.
#inject
, passing an empty string?<<
to combine strings?Try this:
a.map{|t| t.capitalize}.join(" ")
I don't think you can escape from the extra space with inject. Also you need to do
memo = memo + word.capitalize + " "
EDIT: as the statement has changed to force you not to use join and map, here is a bit ugly solution with inject:
a.inject("") do |memo, world|
memo << " " unless memo.empty?
memo << word.capitalize
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With