line = IO.readlines('some_file')
c = rand*line.length.to_i
puts line[c-1]
Very simple logic and it can be easily understood by just looking at the code itself. No explanation needed. If someone knows a better way to do it then please post it in the comments. BTW..thats in ruby.
Advertisements
How about this?
File.open(“myfile.txt”).readlines.shuffle.pop
It uses Ruby’s “readlines” method to read the whole file into an array and the “shuffle” method to mix it up and then pull off the last element (which is now a random line from the file)! 🙂
Actually, it could be even shorter like so:
IO.readlines(“myfile.txt”).shuffle.pop
Great! but I am wondering how did you find such an old post hidden since 2007 🙂
I think I found it by Googling for “ruby random line from file” and it’s one of the top hits 🙂
Same here.
Congrats on the top google search for “ruby random file line”
For the next ruby googler:
IO.readlines(‘/etc/passwd’).sample
Result = returns random line (type String) from file
How it works:
IO.readlines = Reads all of the lines and returns them in an Array
http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-readlines
.sample = Choose a random element or n random elements from an Array
http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-sample
nice one