C# ?? operador en Ruby?
Is there a Ruby operator that does the same thing as C#'s ?? ¿operador?
La ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
preguntado el 09 de enero de 11 a las 03:01
The name of the operator is the operador de coalescencia nula. 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 Aquí.
In short, you can use
||, como en:
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
En lugar de
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|