在 Ruby 中使用正则表达式如果条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9861611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:06:32  来源:igfitidea点击:

Using regex in Ruby if condition

ruby-on-railsruby

提问by Exupery

I'm trying to use regex as the conditional in a Ruby (1.9.2) if statement but it keeps returning true even when the regex evaluates to nil

我试图在 Ruby (1.9.2) if 语句中使用正则表达式作为条件,但即使正则表达式计算为 nil,它也会一直返回 true

if (params[:test] =~ /foo/)
  return "match"
else
  return "no match"
end

The above returns "match" even when Rails.logger.info(params[:test])shows test as set to "bar"

即使Rails.logger.info(params[:test])显示测试设置为,上面也会返回“匹配”"bar"

回答by Zed

if params[:test] =~ /foo/
    # Successful match
else
    # Match attempt failed
end

Works for me. Debug what is in params[:test]

对我来说有效。调试里面的东西params[:test]