¿Ruby es equivalente a C #? operador [duplicado]

Posible duplicado:
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.

desde http://msdn.microsoft.com/en-us/library/ms173224.aspx

preguntado el 09 de enero de 11 a las 03:01

3 Respuestas

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)

contestado el 21 de mayo de 20 a las 02:05

El enlace ahora está muerto. - orourkedd

This is actually a "falsy-coalescing operator". - Kelvin

Link is a 404 again - Michael Lang

Its not the same thing. Does not work for boolean of other falsy values.. - olivervbk

@Cristik Thanks, updated the link hopefully for the last time ever - Chris Pitman

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.

Respondido el 09 de enero de 11 a las 17:01

Lo intenté 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 tiene menor precedencia que = - Shuo

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 - orourkedd

Unfortunately the 2nd snippet could have side-effects if b is a method (i.e. it's called twice). - Kelvin

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

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|

Respondido el 09 de enero de 11 a las 13:01

You'll also often see that as [*x].each do |y|. - Michael Kohl

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.