开发者

Using a Regular Expressions as a conditional loop (until)

开发者 https://www.devze.com 2023-03-24 19:12 出处:网络
I\'m trying to use a regular expression as a condition inside (until) loop. basically, It\'s for entering numeric password..

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 unfortunat开发者_如何学Pythonely it didn't work.

Any ideas?


You shouldn't compare to the string "true". In fact in Ruby you barely ever should need to explicitly compare to true or false, since that's what boolean expressions evaluate to. Also note that to_i probably does not do what you expect:

"adsfasf34".to_i #=> 0
"1adsfasf34".to_i #=> 1

What you can do is something like this:

print "Password: "
until (x = gets.chomp) =~ /^[\d]+(\.[\d]+){0,1}$/
  print "Only numbers allowed, Password: "
end
x = x.to_i


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 if

 (a class of this regex is the same as the class of the string) equals string "true"

The 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 or false will be true! so the regular expression match operator will do just fine (it returns nil 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,

print "Password: "
x = gets.chomp

until /^[\d]+$/ =~ x
  print "Only numbers allowed, Password: "
  x = gets.chomp
end

pw =x.to_i
0

精彩评论

暂无评论...
验证码 换一张
取 消