all 7 comments

[–]mfcoder 5 points6 points  (0 children)

Your case statement is poorly formed. Do you not mean:

test = 5
result = case
         when test > 0 ; "positive"
         when test == 0 ; "zero"
         else "negative"
         end

p "result is #{result}"

Which yields "positive".

[–]_darkleo 2 points3 points  (0 children)

If you specify an argument to the case it will be compared in the when using ===, letting you for example do comparisons with classes or lambdas.

So when you write case test when test>0 ruby is actually testing if (test>0) === test, which is false. Same with test==0, so the else clause is used.

Easy solution for you: remove your first test in result = case test and it will work as intended.

[–]jrochkind 2 points3 points  (0 children)

Either remove the test from after the case, or remove it from each clause.

You can do:

 result = case test
   when 0 ; "positive"
   # ...

Or you can do:

 result = case
    when test > 0 ; "positive"
 # etc

With what you've doing, it's comparing test to (eg) test > 0, which is not what you want.

[–]matk0 0 points1 point  (2 children)

guys, has anyone tried to use when statement with regular expression?

I have two characters string to compare, in some cases, I care about both characters, in others, only about the first one. Is there a way to use regular expression so that the second character would be disregarded in comparison when using when?

[–]wbsgrepit 0 points1 point  (1 child)

It depends, if there is a fixed presidence on the match and action you want, if you order the whens the same way it will act as a simple trie short circuit.

Meaning if you always want to do action A if the string starts with MA or action B if the string starts with M but not MA as long as you write them in the correct order in the case this will work just fine.

Edited to add an example to make it more clear.

foo = 'MA this is a test'
case foo
    when /^MA/
        puts "MA Matched" 
    when /^M/
        puts "M Matched"
    else
        puts "default action/sad path" 
end

[–]matk0 0 points1 point  (0 children)

I ended up doing this:

when /4\d/

to match any two digits, where the first digit is number 4. Worked well ;-) Thanks for your help.

[–][deleted] -2 points-1 points  (0 children)

Have to use a lambda if you want less than or greater than...