Skip to content

Instantly share code, notes, and snippets.

@aliang aliang/io_ext.rb
Created May 7, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.