Ruby:if语句使用regexp和boolean运算符
我正在学习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
这失败了,我不知道为什么。 基本上我希望在处理文件中的行时忽略注释行和空行。 谢谢你的帮助。
你可以写得更简洁,如
puts DATA.readlines.reject{|each|each =~ /^;;|^\s*$/} __END__ ;; alias filename backupDir Prog_i Prog_i.rb ./store Prog_ii Prog_ii.rb ./store
你需要使用AND
基本上你不想not (blank or comment)
在申请DeMorgan后变成not blank and not comment
if (line !~ commentline && line !~ blankline) puts line end
要么
unless(line ~= commentline || line ~= blankline) puts line end
取决于你发现哪些更具可读性
这是你的代码:
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