Using #inject to join strings from an array
There are better ways then #inject
, see the other answers. But if you insist you could just String#rstrip
the trailing space character.
Or turn the block around and check whether memo is empty before adding the character.
memo << " " unless memo.empty?
memo << name.capitalize
I'm not sure about the <<
operator. I would use +
, but that is probably just be a personal preference.
a = ["emperor", "joshua", "abraham", "norton"]
a.drop(1).inject(a.first.capitalize){|res,m| res << ' '+m.capitalize }
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