Aurimas Aurimas - 5 months ago 12
Ruby Question

Ruby equivalent to Coffeescript shortened version of shorthand `if` operator

In coffeescript you can do

name = a ? "bear"
. How can you do this in Ruby?

For those not aware of Coffeescript (v1.10), the statement above translates to Javascript as so:

name = typeof a !== "undefined" && a !== null ? a : "bear"


In other words, if
a
is
undefined
or
null
, then assign
"bear"
to
name
(instead of assigning
a
to
name
)

Answer

Boolean or:

name = a || "bear"

To be precise, the following is an exact equivalent (there is no undefined in ruby):

name = a.nil? ? 'bear' : a