Garry Pettet
Garry Pettet

Reputation: 8288

How can I read lines from a file into an array that are not comments or empty?

I have a text file where a line may be either blank, a comment (begins with //) or an instruction (i.e. anything not blank or a comment). For instance:

Hiya #{prefs("interlocutor")}!

// Say morning appropriately or hi otherwise
#{(0..11).include?(Time.now.hour) ? 'Morning' : 'Hi'} #{prefs("interlocutor")}

I'm trying to read the contents of the file into an array where only the instruction lines are included (i.e. skip the blank lines and comments). I have this code (which works):

path = Pathname.new("test.txt")
# Get each line from the file and reject comment lines
lines = path.readlines.reject{ |line| line.start_with?("//") }.map{ |line| line.chomp }
# Reject blank lines
lines = lines.reject{ |line| line.length == 0 }

Is there a more efficient or elegant way of doing it?

Upvotes: 0

Views: 399

Answers (2)

steenslag
steenslag

Reputation: 80105

start_with takes multiple arguments, so you can do

File.open("test.txt").each_line.reject{|line| line.start_with?("//", "\n")}.map(&:chomp)

in one go.

Upvotes: 2

max pleaner
max pleaner

Reputation: 26788

I would do it like so, using regex:

def read_commands(path)
  File.read(path).split("\n").reduce([]) do |results, line|
    case line
    when /^\s*\/\/.*$/ # check for comments
    when /^\s*$/       # check for empty lines
    else
      results.push line
    end
    results
  end
end

To break down the regexes:

comments_regex = %r{
  ^     # beginning of line
  \s*   # any number of whitespaces
  \/\/  # the // sequence
  .*    # any number of anything
  $     # end of line
}x

empty_lines_regex = %r{
  ^     # beginning of line
  \s*   # any number of whitespaces
  $     # end of line
}x

Upvotes: 0

Related Questions