Search code examples
c#rubynull-coalescing-operator

Ruby's equivalent to C#'s ?? operator


Possible Duplicate:
C# ?? operator in Ruby?

Is there a Ruby operator that does the same thing as C#'s ?? operator?

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

from http://msdn.microsoft.com/en-us/library/ms173224.aspx


Solution

  • The name of the operator is the null-coalescing operator. The original blog post I linked to that covered the differences in null coalescing between languages has been taken down. A newer comparison between C# and Ruby null coalescing can be found here.

    In short, you can use ||, as in:

    a_or_b = (a || b)