jeudi 8 septembre 2016

Ruby file renaming and if syntax

I have two questions regarding the picture downloading program on pp. 108-109 from Chris Pine's book about Ruby. It's supposed to be a program that moves the photos from your camera (in my case it's D:/) to a designated folder, and renames the batch as you want. Here's the code from the book, without some of the comments:

Dir.chdir 'C:/Documents and Settings/Katy/PictureInbox'
# First we find all of the pictures to be moved.
pic_names = Dir['F:/**/*.{JPG,jpg}']
puts 'What would you like to call this batch?'
batch_name = gets.chomp
puts
print "Downloading #{pic_names.length} files: "
# This will be our counter. 
pic_number = 1
pic_names.each do |name|
print '.' # This is our "progress bar".
new_name = if pic_number < 10
"batch_name0#{pic_number}.jpg"
else
"batch_name#{pic_number}.jpg"
end
File.rename name, new_name
# Finally, we increment the counter.
pic_number = pic_number + 1
end
puts # This is so we aren't on progress bar line.
puts 'Done, cutie!'

My first question is about the following passage:

new_name = if pic_number < 10
"batch_name0#{pic_number}.jpg"
else
"batch_name#{pic_number}.jpg"
end

The program didn't run for me, unless I changed it to the syntax I was familiar with:

if pic_number < 10
new_name = "batch_name0#{pic_number}.jpg"
else
new_name = "batch_name#{pic_number}.jpg"
end

Everything worked fine then. Although for some reason it changed the order of the photos.

My question is - is the syntax mentioned in the book wrong or the reason for it not working is different? This is also the first instance I see of similar syntax being used in the book.

Another problem I had was that I first named the batch "Sony", with a capital s, and the photos got deleted from the camera and were not moved to the folder (in my case it was C:/CameraPhotos).

When I tried to name the batch "sony", it worked properly. After that I tried adding to_s to the batch_name: "batch_name = gets.chomp.to_s", and it worked with the capital S. Does this have anything to do with the use of capital letters in Ruby, or the reason is different?

The final code of my program is, just in case:

Dir.chdir 'C:/CameraPhotos'
pic_names = Dir['D:/**/*.jpg']
puts 'What would you like to call hits batch?'
batch_name = gets.chomp.to_s
puts
print "Downloading #{pic_names.length} files: "
pic_number = 1

pic_names.each do |name|
print '.'
if pic_number < 10
new_name =  "#{batch_name}0#{pic_number}.jpg"
else
new_name = "#{batch_name}#{pic_number}.jpg"
end
File.rename name, new_name
pic_number = pic_number + 1
end
puts
puts 'Done!'

Aucun commentaire:

Enregistrer un commentaire