I/O Exercises - File Shuffler

In the file shuffler solution, it seems that a new blank file is opened with the word “shuffled” tacked on to the file name. Then, an array of lines of the original file is created, the array is shuffled, and then each line is put into into the “shuffled” file one by one.
def file_shuffler(file)
base = File.basename(file, “.*”)
ext = File.extname(file)
File.open("#{base}-shuffled#{ext}", “w”) do |f|
File.readlines(file).shuffle.each do |line|
f.puts line
end
end
end

Can it be done differently? Could the file be duplicated then the lines shuffled? I tried the following code which seemed to work but it doesn’t seem to actually save it to the file. It just seems to print the shuffled contents to the screen.

def file_shuffler(file)
base = File.basename(file, “.*”)
ext = File.extname(file)
File.open("#{base}-shuffled#{ext}", “w”) do |f|
File.readlines(file).each do |line|
f.puts line
end
File.readlines("#{base}-shuffled#{ext}").shuffle
end
end

Is the file not being properly closed? Or is it only printing an array to the screen?
Is there some easier way to duplicate the file using .clone or .dup?

Hi gabeross,

If you want to make any changes to the file, you have to use File.open("insert_file_name", "w"). In your second scenario, to copy the file over and then shuffle, you have to run File.open twice. First to copy the file over and second to overwrite and shuffle the lines. Of course, this is not efficient and you can perform both the copying over and shuffling in one File.open method by following the solution method.
So to answer your last two questions: it is only printing the array to the screen because the last line ran is to File.readlines which forms an array of each line in the file. There are easier ways to copy files using the FileUtils class but that is outside the scope of this course. However, you are free to explore more on this topic when you have the time.

Michael Ruan
Alpha Course TA