ruby renames the elements of the array with different array elements

advertisements

i have a file that looks like this:

TTITLE0=track name 1
TTITLE1=track name 2

and a directory that contains track01.cdda.wav.mp3 and track02.cdda.wav.mp3

i have the following code, which creates 2 different arrays, 1 with the track names and 1 with the track titles:

tracks = Dir.glob("*.mp3")

tracknames = Array.new
File.open('read').each do |line|
  if line =~ /TTITLE/
    tracknames << line.split("=")[1].strip!
  end
end

this gives me 2 arrays:

["track name 1", "track name 2"]

and

["track01.cdda.wav.mp3", "track02.cdda.wav.mp3"]

i would like to rename the files in the second array with the elements of the first array. so, "track01.cdda.wav.mp3" would become "track name 1.mp3".

here is what i have tried so far:

tracks.map {|track| File.rename("#{tracks}", "#{tracknames}.mp3") }

and i get the error:

No such file or directory - track01.cdda.wav.mp3track02.cdda.wav.mp3 or track name 1track name 2 (Errno::ENOENT)

i have to keep in mind that in the future there could be any number of elements in each array, but the numbers will be equal to each other.

any ideas?


Use Array#zip:

tracks.zip(tracknames).each do |track, trackname|
  File.rename track, "#{trackname}.mp3"
end

Alternatively (less fun, but doesn't create an intermediary array of arrays prior to enumeration):

tracks.each_with_index do |track, i|
  File.rename track, "#{tracknames[i]}.mp3"
end