Skip to main content
2 of 7
added refactored code
pgreen2
  • 639
  • 3
  • 13

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

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
}

Update:

Refactored Code:

File.open('english-words-partial.txt', 'w') do |file|
    File.readlines('english-words-full.txt').each do |line|
        file.puts(line) if rand(1..10) == 1
    end
end
pgreen2
  • 639
  • 3
  • 13