Darek Rossman Darek Rossman - 2 years ago 59
Ruby Question

Using #inject to join strings from an array

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
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
, 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 << " "

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
    , passing an empty string?

  • Am I making correct use of the
    to combine strings?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download