1

Is there a standard method in Ruby to prepend and/or append a string onto each of an array of strings?

listOfnames = [ 'john', 'dave', 'joe' ];    
mrNames = prependToAll('Mr. ', list of names);

resulting in [ 'Mr. john', 'Mr. dave', 'Mr. joe' ]

Is there a version to do so in place?

Or is there a standard way for some easy each to replace array entries in the array being iterated over?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
peterk
  • 5,136
  • 6
  • 33
  • 47

3 Answers3

8
listOfnames.map {|name| "Mr. " + name}

If you need to edit the listOfnames variable, use the destructive version of map:

listOfnames.map! {|name| "Mr. " + name}
Zippie
  • 6,018
  • 6
  • 31
  • 46
2

There is prepend, but not for an array.

%w[john dave joe].map{|s| s.prepend("Mr. ")}
# => ["Mr. john", "Mr. dave", "Mr. joe"]
sawa
  • 165,429
  • 45
  • 277
  • 381
1

Same result using Array#product

["Mr. "].product(listOfNames).map(&:join)
dotpao
  • 106
  • 1
  • 3