Shuffled standard input or shuffled files

by Carson Reynolds

Every now and then I like to shuffle a file or a directory. Here is a trivial shuffle script in Ruby:


# output randomly shuffled lines from the file passed as an argument
# or input fed to standard input
# ex: ls | shuffle.rb 
# This produces a randomly shuffled directory

# a modified version of the code from
# shuffle modified from "Programming in Ruby" by Thomas and Hunt

# get the lines:
if ARGV.size == 1
  lines = IO.readlines(ARGV[0])
elsif not ARGF.eof?
  lines = ARGF.readlines
  abort "usage: shuffle.rb <file>"

# pick a random line, remove it, and print it
lines.size.times do
  print lines.delete_at(rand(lines.size))