Reputation: 21
I would like to run x if y
if z
is true, and x unless y
if z is false.
What's the most idiomatic way to do that? The best I can come up with is:
x if z ? y : !y
Upvotes: 2
Views: 1409
Reputation: 81691
Use the xor operator, and then negate it:
x unless (!y ^ !z)
Corrected based on Victor suggestion, as things that aren't true
, false
or nil
may do their own thing with ^
.
Upvotes: 4
Reputation: 17656
That seems like a confusing way of thinking about this. To me the clearer formulation (Ruby-ish or otherwise) is
x if (z and y) or (not z and not y)
Upvotes: 1
Reputation: 311765
Try this:
x if !!y == !!z
This is a standard Ruby idiom for coercing to boolean values. If y
and z
are already booleans, then you can simply do:
x if y == z
Upvotes: 6