gpt4 book ai didi

Ruby:使用正则表达式和 bool 运算符的 if 语句

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:51 26 4
gpt4 key购买 nike

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

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

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

最佳答案

你需要使用一个 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

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

关于Ruby:使用正则表达式和 bool 运算符的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com