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?
string arrays ruby inject
Darek rossman
source share