MrRobot MrRobot - 4 months ago 5x
Ruby Question

Ruby code to look for a specific file,and rename it,doesn't work?

I am trying to generate thumbnails with Ruby,on a linux machine.

The process,includes determining which of the 5 thumbnails,already generated,is the most meaningful(by meaningful,here,i meant to pick the one with the highest size,since a bigger size means more details).

Afterwards i went to rename the file having the biggest size into a generic name in order to use it later.The code doesn't seem to be working for me,and i can't understand the reason,is there any suggestions to improve it?

Thank you in advance.

Here is my code:

For your possible needs, the variable

contains the path of the directory we are getting the thumbnails,from.

max = File.size("#{thumb_dir}/thumb01.jpg").to_f #
name = "thumb01.jpg"

for i in 2..5
if max < File.size("#{thumb_dir}/thumb0'"#{i}"'.jpg" ).to_f?
max = File.size("#{thumb_dir}/thumb0'"{i}"'.jpg"
name = "thumb0" + "#{i}" + ".jpg"

File.rename("#{thumb_dir}/#{name}", "thumbnail.jpg") `

i = (1..5).map {|i| File.size("#{thumb_dir}/thumb#{i}.jpg").to_f }.each_with_index.max[1]

File.rename("#{thumb_dir}/thumb#{i + 1}.jpg", "thumbnail.jpg")

What does it do ?

  1. (1..5).map {|i| File.size("#{thumb_dir}/thumb#{i}.jpg").to_f }

We get an array of file sizes for thumb1.jpg up to thumb5.jpg

  1. array.each_with_index.max[1]

Used to get the index of the greatest value of the array.

  1. File.rename("#{thumb_dir}/thumb#{i+1}.jpg", "thumbnail.jpg")

Now that we know that i is the index of the greatest value in the array, then thumb#{(i+1)}.jpg is the file with the greatest size, so that's the one we want to replace the name of.