[英]How can I put RegExp in ruby's case condition?
something like this:像这样的东西:
a = 6
case a
when /\d/ then "it's a number"
end
no luck, it doesn't work没有运气,它不起作用
It doesn't work because regexes match against a string, whereas 6 is not a string.它不起作用,因为正则表达式匹配字符串,而 6 不是字符串。 If you do
a = '6'
, it shall work.如果您执行
a = '6'
,它将起作用。
When used with a value on the initializer, all case does is try it with === against each expression.当与初始化器上的值一起使用时,所有 case 都是用 === 对每个表达式进行尝试。 The problem isn't with case, try:
问题不在于大小写,请尝试:
6 === /\d/
All that to say, regexes match against strings only.综上所述,正则表达式仅与字符串匹配。 Try replacing the second line by:
尝试将第二行替换为:
case (a.is_a?(String) ? a : a.to_s)
EDIT : To answer the OP's follow-up in comments, there's a subtlety here.编辑:为了回答 OP 在评论中的后续行动,这里有一个微妙之处。
/\d/ === '6' # => true
'6' === /\d/ # => false
Perhaps unexpectedly to the beginner, String#=== and Regexp#=== have different effects.可能对初学者来说出乎意料的是,String#=== 和 Regexp#=== 有不同的效果。 So, for:
因此对于:
case 'foo'
when String
end
This will call String === 'foo'
, not 'foo' === String
, etc.这将调用
String === 'foo'
,而不是'foo' === String
等。
Because regexps match strings.因为正则表达式匹配字符串。 A is a Fixnum.
A是一个Fixnum。
If you would write a = "6"
, it would work.如果你写
a = "6"
,它会工作。 Testing if a is a number can be done with a.is_a?(Numeric)
可以使用
a.is_a?(Numeric)
测试 a 是否为数字
One minor change to make it work:使其工作的一个小改动:
a = 6
case a.to_s
when /\d/ then "it's a number"
end
The to_s will convert everything to a string. to_s 会将所有内容转换为字符串。 Note that your regex just checks for the existence of a digit anywhere in the string.
请注意,您的正则表达式仅检查字符串中任何位置是否存在数字。
It would perhaps be better to do this:这样做可能会更好:
case a
when Numeric then "it's a number"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.