Ruby - How to skip/ignore specific lines when reading a file?

user2253130 picture user2253130 · Apr 13, 2013 · Viewed 9k times · Source

What's the best approach for ignoring some lines when reading/parsing a file (using Ruby)?

I'm trying to parse just the Scenarios from a Cucumber .feature file and would like to skip lines that doesn't start with the words Scenario/Given/When/Then/And/But.

The code below works but it's ridiculous, so I'm looking for a smart solution :)

File.open(file).each_line do |line|
  line.chomp!
  next if line.empty? 
  next if line.include? "#"
  next if line.include? "Feature" 
  next if line.include? "In order" 
  next if line.include? "As a" 
  next if line.include? "I want"

Answer

fmendez picture fmendez · Apr 13, 2013

You could do it like this:

a = ["#","Feature","In order","As a","I want"]   
File.open(file).each_line do |line|
  line.chomp!
  next if line.empty? || a.any? { |a| line =~ /#{a}/ }
end