Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 #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?
like image 401
Darek Rossman Avatar asked Mar 14 '12 13:03

Darek Rossman


1 Answers

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
like image 66
Ivaylo Strandjev Avatar answered Sep 29 '22 10:09

Ivaylo Strandjev