Ruby's equivalent to C#'s ?? operator
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)
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.
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|