使用正则表达式作为条件循环(直到)
我正在尝试使用正则表达式作为(直到)循环内的条件。 基本上,它用于输入数字密码。
我尝试了这段代码
print "Password: "
x = gets.chomp.to_i
until (/^[\d]+(\.[\d]+){0,1}$/ === "#{x}") == "true"
print "Only numbers allowed, Password: "
x = gets.chomp.to_i
end
,但不幸的是它不起作用。
有什么想法吗?
I'm trying to use a regular expression as a condition inside (until) loop.
basically, It's for entering numeric password..
I tried this code
print "Password: "
x = gets.chomp.to_i
until (/^[\d]+(\.[\d]+){0,1}$/ === "#{x}") == "true"
print "Only numbers allowed, Password: "
x = gets.chomp.to_i
end
but unfortunately it didn't work.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该与字符串
"true"
进行比较。事实上,在 Ruby 中,您几乎不需要显式地与true
或false
进行比较,因为这就是布尔表达式的计算结果。另请注意,to_i
可能不会执行您期望的操作:您可以执行以下操作:
You shouldn't compare to the string
"true"
. In fact in Ruby you barely ever should need to explicitly compare totrue
orfalse
, since that's what boolean expressions evaluate to. Also note thatto_i
probably does not do what you expect:What you can do is something like this:
当然这是行不通的。
===
("triqual") 相当于“Is of the same class as”。所以你要做的就是询问 Ruby 如果这种情况下的内部比较是拙劣的并且从一开始就无法工作(正则表达式和字符串无论如何都不是同一类),外部比较也永远不会工作(Ruby 没有神奇的字符串常量,如 ECMAscript 的
undefined
)。对于 Ruby 中的条件语句,记住这一点很容易:任何计算结果为
nil
或false
以外的值的表达式都将为 true!因此正则表达式匹配运算符就可以了(当没有找到匹配项时,它返回nil,这就是您要查找的内容,以及找到匹配项时的偏移量 - 以及中的任何整数) Ruby 是“真实的”,甚至是 0)。所以确实,
Of course this doesn't work.
===
("triqual") is the equivalent "Is of the same class as". So what you are doing there is asking Ruby ifThe inner comparison in this case is botched and would never work to begin with (Regexp and a string are never of the same class anyway), the outer one would never work either (Ruby has no magic string constants like ECMAscript's
undefined
).For conditionals in Ruby it's handy to remember this: any expression evaluating to anything else than
nil
orfalse
will be true! so the regular expression match operator will do just fine (it returnsnil
when no matches are found, which is what you are looking for, and the offset at which the match is when found - and any integer in Ruby is "trueish", even 0).So indeed,