Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pre-pend to each element in an array in Ruby

Is there a way to prepend each element of an array with something.

eg:

file = File.new(my_file,'r')

header = IO.readlines(my_file)[1]  # header looks like [1,2,3]
#Prepend each elelement of header with filename, something like
header.prepend(filename+".")     #header looks like [filename.1,filename.2,filename.3]
like image 685
codeObserver Avatar asked Dec 02 '11 02:12

codeObserver


1 Answers

You want to use map:

["foo", "bar", "baz"].map { |word| "prepend-#{word}" }
#=> ["prepend-foo", "prepend-bar", "prepend-baz"]

classic case for this method. This method can also take an array containing elements of any type.

like image 51
bkempner Avatar answered Sep 23 '22 06:09

bkempner