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

11,552

Solution 1

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)

Solution 2

If you don't mind coalescing false, you can use the || operator:

a = b || c

If false can be a valid value, you can do:

a = b.nil? ? c : b

Where b is checked for nil, and if it is, a is assigned the value of c, and if not, b.

Solution 3

Be aware that Ruby has specific features for the usual null coalescing to [] or 0 or 0.0.

Instead of

x = y || [] # or...
x = y || 0

...you can (because NilClass implements them) just do...

x = y.to_a # => [] or ..
x = y.to_i # or .to_f, => 0

This makes certain common design patterns like:

(x || []).each do |y|

...look a bit nicer:

x.to_a.each do |y|
Share:
11,552
Shuo
Author by

Shuo

Updated on June 14, 2022

Comments

  • Shuo
    Shuo about 2 years

    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

  • Shuo
    Shuo over 13 years
    I tried a = b or c; puts a. Surprise, surprise, in my ruby 1.8.6, it prints the value of b. The reason is that or has lower precedence than =
  • Michael Kohl
    Michael Kohl over 13 years
    You'll also often see that as [*x].each do |y|.
  • orourkedd
    orourkedd over 10 years
    The link is now dead.
  • orourkedd
    orourkedd over 10 years
    or is not a boolean operator but a control flow operator in ruby: devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby
  • Chris Pitman
    Chris Pitman over 10 years
    @orourkedd Thanks, I've reworked it a bit with a new link.
  • Kelvin
    Kelvin almost 9 years
    Unfortunately the 2nd snippet could have side-effects if b is a method (i.e. it's called twice).
  • Kelvin
    Kelvin almost 9 years
    This is actually a "falsy-coalescing operator".
  • Michael Lang
    Michael Lang almost 8 years
    Link is a 404 again
  • olivervbk
    olivervbk about 7 years
    Its not the same thing. Does not work for boolean of other falsy values..
  • Mayuresh Srivastava
    Mayuresh Srivastava over 6 years
    according to this chrisarcand.com/… this is not null-coalescing operator. ||= is a conditional assignment operator. Is this article right?
  • Chris Pitman
    Chris Pitman over 6 years
    ||= is different from ||
  • Chris Pitman
    Chris Pitman about 4 years
    @Cristik Thanks, updated the link hopefully for the last time ever