简体   繁体   中英

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 (ie 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 (ie 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? Thanks.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM