1

我正在学习 Ruby,但未能使复合“if”语句起作用。这是我的代码(希望不言自明)

commentline = Regexp.new('^;;') 
blankline = Regexp.new('^(\s*)$')

if (line !~ commentline || line !~ blankline)
  puts line
end

变量“line”是通过读取以下文件获得的:

;; alias filename backupDir

Prog_i  Prog_i.rb ./store
Prog_ii Prog_ii.rb ./store

这失败了,我不确定为什么。基本上我希望在处理文件中的行期间忽略注释行和空白行。谢谢你的帮助。

4

3 回答 3

6

你需要使用 AND

基本上你想要在应用DeMorgannot (blank or comment)之后变成not blank and not comment

if (line !~ commentline && line !~ blankline)
  puts line
end

或者

unless(line ~= commentline || line ~= blankline)
  puts line
end

取决于你觉得哪个更具可读性

于 2012-12-07T00:08:57.020 回答
1

你可以写得更简洁,因为

puts DATA.readlines.reject{|each|each =~ /^;;|^\s*$/}

__END__
;; alias filename backupDir

Prog_i  Prog_i.rb ./store
Prog_ii Prog_ii.rb ./store
于 2012-12-07T01:15:15.943 回答
1

这是你的代码:

commentline = Regexp.new('^;;') 
blankline = Regexp.new('^(\s*)$')

if (line !~ commentline || line !~ blankline)
  puts line
end

以及我如何写同样的东西:

[
  ';; alias filename backupDir',
  '',
  'Prog_i  Prog_i.rb ./store',
  'Prog_ii Prog_ii.rb ./store'
].each do |line|

  puts line if (!line[/^(?:;;)?$/])

end

哪个输出:

;; alias filename backupDir
Prog_i  Prog_i.rb ./store
Prog_ii Prog_ii.rb ./store
于 2012-12-07T02:08:38.247 回答