Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 821
user2253130 Avatar asked Apr 13 '13 21:04

user2253130


People also ask

How do you skip to the next line in text?

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.

How do I read a file line by line in Ruby?

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.


2 Answers

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
like image 111
fmendez Avatar answered Oct 21 '22 08:10

fmendez


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
like image 4
steenslag Avatar answered Oct 21 '22 09:10

steenslag