Ruby's equivalent to C#'s ?? operator
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|
Shuo
Updated on June 14, 2022Comments
-
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.
-
Shuo over 13 yearsI tried
a = b or c; puts a
. Surprise, surprise, in my ruby 1.8.6, it prints the value of b. The reason is thator
has lower precedence than=
-
Michael Kohl over 13 yearsYou'll also often see that as
[*x].each do |y|
. -
orourkedd over 10 yearsThe link is now dead.
-
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 over 10 years@orourkedd Thanks, I've reworked it a bit with a new link.
-
Kelvin almost 9 yearsUnfortunately the 2nd snippet could have side-effects if
b
is a method (i.e. it's called twice). -
Kelvin almost 9 yearsThis is actually a "falsy-coalescing operator".
-
Michael Lang almost 8 yearsLink is a 404 again
-
olivervbk about 7 yearsIts not the same thing. Does not work for boolean of other falsy values..
-
Mayuresh Srivastava over 6 yearsaccording to this chrisarcand.com/… this is not null-coalescing operator. ||= is a conditional assignment operator. Is this article right?
-
Chris Pitman over 6 years||= is different from ||
-
Chris Pitman about 4 years@Cristik Thanks, updated the link hopefully for the last time ever