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

What is the best approach to ignore some lines when reading / analyzing a file (using Ruby)?

I am trying to parse only the scripts from the Cucumber.feature file and would like to skip lines that do not start with the words Scenario / Given / When / Then / And / But.

The code below works, but it's funny, 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"
+5
source share
5 answers

You can do it as follows:

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
+5
source

The method start_with?takes several arguments:

File.open(file).each_line do |line|
  next unless line.start_with? 'Scenario', 'Given', 'When', 'Then', 'And', 'But'
  # do something with line.
end
+3
source

, . String # chomp! . :

File.open(file).each do |line|
  next if line.chomp! =~ /^$|#|Feature|In order|As a|I want/
  # something else
end

This reduces your block by six lines of code. Regardless of whether you find this alternative easier to read, it is, of course, shorter and slightly more idiomatic. Your mileage may vary.

+1
source

This doesn't help much, but well, you can use array intersection for less code.

words = ["#", "Feature", "In order", "As a", "I want"]

File.open(file).each_line do |line|
  line.chomp!
  next if line.empty? || !(line.split & words).empty?
0
source

Use the refctoring method abstract method! In an abstract method, you could use any technique, smart or not very smart.

File.open(file).each_line do |line|
         line.chomp!
         next if ignore(line)
end

def ignore line
#do whatever you like here, clever or straightforward. 
#All the techniques others has posted could be applied here
end
0
source

All Articles