简体   繁体   中英

ruby case statement with strings doesn't work (as expected)

case 'this is not a test' 
  when 'this is not a test'.eql?('this is not a test')
    p '1' 
end

This does not match.

I've also tried:

  1. my_var = 'this is not a test' and changing the case statement appropriately.
  2. doing #1 coupled with various "#{my_var}" tries.
  3. printing everything to see if anything is returning anything weird (nil, etc.)
  4. using IRB to test 1, 2 and 3.

Of course it does not match.

  • 'this is not a test'.eql?('this is not a test') evaluates to true .

  • case x when y .... end evaluates to if y === x ... end .

  • true === 'this is not a test' evaluates to false .

You either wanted case when x ... end , which evaluates to if x ... end , a slightly different syntax with a different semantics:

case
  when 'this is not a test'.eql?('this is not a test')
    p '1' 
end

or, if you're happy with === instead of eql? , you can write

case 'this is not a test'
  when 'this is not a test'
    p '1' 
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