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?