Ruby: why this WHEN-statement doesn't work with two conditions?

4124 views ruby
2

I have a case in my Ruby code that basically tries to match string in a couple of ways and do different things to it accordingly, kind of like that:

case inst
when Rx_inst1
  (some function)
when Rx_inst2
  (some other function)
end

This works beautifully (I'm not posting the RegEx as it's very, very long and works well). However, when I tried implementing the following modification, so that even when the RegEx matches a string, the condition is not executed if it contains a substring:

case inst
when Rx_inst1
  (some function)
when Rx_inst2 && !/dom\./
  (some other function)
end

it Rx_inst2 stopped matching inst when it was equal Nm. Friese = Fryzyjczyk, ko? fryzyjski or any other kind of string it matched before.

I got the exact same result with && /dom\./ and && inst.include?('dom.') which, according to other answers, are proper syntax. What am I doing wrong?

answered question

1 Answer

10

It's pretty obvious, Rx_inst2 && !/dom\./ returns (due to short circuit evaluation) only the second operand, which is !/dom\/ (provided Rx_inst2 is indeed a Regexp and thus not falsy). You probably need to modify this regexp in Rx_inst2, there's no short answer.

posted this

Have an answer?

JD

Please login first before posting an answer.