Skip to content

Instantly share code, notes, and snippets.

@aliang
Created May 7, 2014 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliang/98688024b7c0963e8d9a to your computer and use it in GitHub Desktop.
Save aliang/98688024b7c0963e8d9a to your computer and use it in GitHub Desktop.
Select random line from IO object
# See http://stackoverflow.com/questions/11007111/ruby-whats-an-elegant-way-to-pick-a-random-line-from-a-text-file
class IO
# Selects a random "line" from a file (might not be a line if different separator is passed).
# @param *args Same arguments as IO.foreach
# @return A random line from the IO object
def self.random_line(*args)
chosen_line = nil
self.foreach(*args).each_with_index do |line, number|
chosen_line = line if rand < 1.0/(number+1)
end
chosen_line
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment