[via Spinning the Web] In .NET 2.0, C# has a "Coalesce" operator, which is represented by ??
. It it returns the first non-null item from a group of two or more objects.
In case that explanation above doesn't make my meaning clear, this code example will. The following C# code:
return object1 ?? object2 ?? object3
can be used instead of this lengthier code:
if (object1 != null) { return object1; } else if (object2 != null) { return object2; } else if (object3 != null) { return object3; } else { return null; }
This is old hat for Python and Ruby coders. In Python, here's the equivalent code:
return x or y or z
It'll return the first object whose value is not None
, or None
if all the objects have that value.
In Ruby, the equivalent is:
x || y || z
I don't know about the Python example, but the Ruby example isn't quite accurate. If Ruby's || did exactly the same as C#'s ??, the following expression:
x = false; y = true; x || y
... would have the value false (because false is non-nil), rather than its actual value: true.
In Ruby, nil and false evaluate to "false" in a Boolean context and anything else is "true". The || operator tests for "falseness", not "nilness".
</pedantry>
irb
, I didn't test by setting values tofalse
. My bad.I'd hardly call the correction pedantic; I'd simply call it correct. I'll post a correction. Thanks for the heads-up!
I can see why it might have been designed that way (not least because I don't think Python had a Boolean type until quite recently) but I think I prefer Ruby's approach.