Ruby 相当于 shorthand `if` 运算符的 Coffeescript 缩短版

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

在 coffeescript 中你可以做到 name = a ? "bear"。你怎么能在 Ruby 中做到这一点?

对于那些不了解 Coffeescript (v1.10) 的人,上面的语句转换为 Javascript 如下:

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

换句话说,如果aundefinednull,则将"bear"分配给name(而不是分配aname)

布尔值or:

name = a || "bear"

准确的说,下面是完全等价的(ruby中没有undefined):

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