HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyMinor

Generate random 10% of file to be used in testing with Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomfilewithusedgeneratetestingruby

Problem

I'm new to Ruby, but not to programming. I just need a simple script that, given a text file, will pull out around 10% of the lines at random. Below is what I came up with based upon a Python script I wrote. What do I need to do differently to make it more Ruby-like?

prng = Random.new

File.open('english-words-partial.txt', 'w') {  |f| 
  File.readlines('english-words-full.txt').each do |line| 
    if prng.rand >= 0.9
      f.write(line) 
    end
  end
}

Solution

Here's my shot at it:

File.open('english-words-partial.txt', 'w') do |file|
    File.foreach('english-words-full.txt') do |line|
        file.puts(line) if rand(10) == 0
    end
end


In Ruby, you can add an if statement to the end of a line, to conditionally execute that line. This also works with the unless statement.

Also, the rand function can take a number, and produce that many possible numbers from it. So rand(10) will give you a random number from 0 to 9

In Ruby, you usually want to use { } for 1 line blocks, and do/end for multiline blocks, but they both act slightly different. Theres more on that here: https://stackoverflow.com/questions/5587264/do-end-vs-curly-braces-for-blocks-in-ruby

File.foreach('...') is just a bit shorter and neater then File.readlines('...').each (thanks to @Flambino for this)

And lastly, you can use IO methods on a file object like print and puts, so I liked that better but file.write works too. Thats really personal preference.

Code Snippets

File.open('english-words-partial.txt', 'w') do |file|
    File.foreach('english-words-full.txt') do |line|
        file.puts(line) if rand(10) == 0
    end
end

Context

StackExchange Code Review Q#55946, answer score: 6

Revisions (0)

No revisions yet.