AZR
AZR

Reputation: 21

Is there an idiomatic Ruby way to do "if" or "unless" based on a truth value?

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

Answers (3)

Andrew Grimm
Andrew Grimm

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

bnaul
bnaul

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

John Feminella
John Feminella

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

Related Questions