Ruby:if语句使用regexp和boolean operator

bev*_*bev 1 ruby

我正在学习Ruby并且未能使复合'if'语句起作用.这是我的代码(希望自我解释)

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

if (line !~ commentline || line !~ blankline)
  puts line
end
Run Code Online (Sandbox Code Playgroud)

通过读取以下文件获得变量'line':

;; alias filename backupDir

Prog_i  Prog_i.rb ./store
Prog_ii Prog_ii.rb ./store
Run Code Online (Sandbox Code Playgroud)

这失败了,我不知道为什么.基本上我希望在处理文件中的行时忽略注释行和空行.谢谢你的帮助.

rat*_*eak 6

你需要使用AND

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

if (line !~ commentline && line !~ blankline)
  puts line
end
Run Code Online (Sandbox Code Playgroud)

要么

unless(line ~= commentline || line ~= blankline)
  puts line
end
Run Code Online (Sandbox Code Playgroud)

取决于你发现哪些更具可读性