Using #inject to concatenate strings from an array

I am experiencing an online lesson that usually has a very simple one-line solution. The problem is that, given the following array:

["emperor", "joshua", "abraham", "norton"] 

I have to use #inject to get one line from all the names connected with the line, each name is an initial constraint, for example:

 "Emperor Joshua Abraham Norton" 

Although this can easily be done with #map and #join , this particular exercise only requires #inject. 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 spaces at the end of the line do not pass as the correct solution.

  • How can I achieve this without spaces at the end?
  • Is this even the right way to use #inject by passing an empty string?
  • Am I using << to concatenate strings correctly?
+8
string arrays ruby inject
source share
6 answers

Try the following:

 a.map{|t| t.capitalize}.join(" ") 

I do not think that you can escape from the extra space by injection. Also you need to do

 memo = memo + word.capitalize + " " 

EDIT: as the operator has changed to make you not use the connection and map, here is a slightly ugly solution with an injection:

 a.inject("") do |memo, world| memo << " " unless memo.empty? memo << word.capitalize end 
+7
source share
 a = ["emperor", "joshua", "abraham", "norton"] a.drop(1).inject(a.first.capitalize){|res,m| res << ' '+m.capitalize } 
+2
source share

There are better ways and then #inject , see other answers. But if you insist that you can just String#rstrip the mileage character.

Or turn on the block and check if memo is left before adding a character.

 memo << " " unless memo.empty? memo << name.capitalize 

I'm not sure about << . I would use + , but this is probably just a personal preference.

+1
source share

Checking adding a " " every move is more expensive than chop! last exit. Your choice of << correct, you can see the string concatenation .

 irb(main):021:0> %w(emperor joshua abraham norton).inject("") do |m,w| m << w.capitalize << " " end.chop! "Emperor Joshua Abraham Norton" 
+1
source share

Do not use #inject , there are more efficient ways to solve this problem:

 ["emperor", "joshua", "abraham", "norton"].map(&:capitalize).join(' ') 

Your first goal should always be to solve the problem. You can use #inject , but this is simply not an ideal or even clear solution here. You have better things to do with your time than trying to figure out how to trick #inject into giving you the right results.

0
source share

puts x.inject {| memo, val | "# {memo} # {val.upcase}"}

0
source share

All Articles