简体   繁体   中英

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. If you do a = '6' , it shall work.

When used with a value on the initializer, all case does is try it with === against each expression. 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.

/\d/ === '6' # => true
'6' === /\d/ # => false

Perhaps unexpectedly to the beginner, String#=== and Regexp#=== have different effects. So, for:

case 'foo'
when String
end

This will call String === 'foo' , not 'foo' === String , etc.

Because regexps match strings. A is a Fixnum.

If you would write a = "6" , it would work. Testing if a is a number can be done with a.is_a?(Numeric)

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM