ruby 如何将文件中的行读入数组,但这些行不是注解或空的?

dsekswqp  于 2023-04-11  发布在  Ruby
关注(0)|答案(2)|浏览(103)

我有一个文本文件,其中一行可以是空白的,注解(以//开头)或指令(即任何空白或注解)。例如:

Hiya #{prefs("interlocutor")}!

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

我试图将文件的内容读入一个数组,其中只包含指令行(即跳过空行和注解)。我有以下代码(可以工作):

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 }

有没有更有效或更优雅的方法来做这件事?

soat7uwm

soat7uwm1#

start_with接受多个参数,因此您可以

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

一气呵成。

xa9qqrwz

xa9qqrwz2#

我会这样做,使用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

要分解正则表达式:

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

相关问题