Using #inject to join strings from an array

Darek Rossman picture Darek Rossman · Mar 14, 2012 · Viewed 9.5k times · Source

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?

Answer

Ivaylo Strandjev picture Ivaylo Strandjev · Mar 14, 2012

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