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"
To add spacing between lines or paragraphs of text in a cell, use a keyboard shortcut to add a new line. Click the location where you want to break the line. Press ALT+ENTER to insert the line break.
Overview. The IO instance is the basis for all input and output operations in Ruby. Using this instance, we can read a file and get its contents line by line using the foreach() method. This method takes the name of the file, and then a block which gives us access to each line of the contents of the file.
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
The start_with?
method accepts multiple arguments:
File.open(file).each_line do |line|
next unless line.start_with? 'Scenario', 'Given', 'When', 'Then', 'And', 'But'
# do something with line.
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With