Search code examples
rubyparsingcucumberlinesskip

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


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"

Solution

  • 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