Getting a random line from a file – and a question!!!


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

7 thoughts on “Getting a random line from a file – and a question!!!

  1. Peter K. says:

    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)! 🙂

  2. Griffith says:

    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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s