rubyoperatorsnull-coalescing-operator

C# ?? operator in Ruby?


Is it possible to implement the ?? operator in Ruby?

a = nil
b = 1

x = a ?? b # x should == 1
x = b ?? 2 # x should == 1

Solution

  • You're looking for conditional assignment:

    a ||= b  # Assign if a isn't already set
    

    and the || operator

    a = b || 2 # Assign if b is assigned, or assign 2