Created
May 7, 2014 22:47
-
-
Save aliang/98688024b7c0963e8d9a to your computer and use it in GitHub Desktop.
Select random line from IO object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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