【问题标题】:Ruby equivalent to Coffeescript shortened version of shorthand `if` operatorRuby 等价于 Coffeescript 简化版的速记“if”运算符
【发布时间】:2016-10-24 14:32:43
【问题描述】:

在coffeescript 中,您可以使用name = a ? "bear"。你如何在 Ruby 中做到这一点?

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

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

换句话说,如果a 是undefined 或null,则将"bear" 分配给name(而不是将a 分配给name)

【问题讨论】:

  • 对于我们这些没有记住整个 CoffeeScript 语言规范的人,您介意解释一下“Ruby 等效”应该做什么吗?
  • 更新了描述。看起来不错?

标签: ruby coffeescript conditional-operator


【解决方案1】:

布尔值or:

name = a || "bear"

确切地说,以下是完全等价的(ruby 中没有undefined):

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

【讨论】:

  • 我想我必须接受这一点,尽管我真正需要的是 Ruby 等价于 Javascript Boolean or。那就是我需要(0 || "something") 返回“某物”,而不是返回0。问错了我猜的问题:)
  • @Aurimas 注意CoffeeScript 中的0 ? "something" 也返回0,它不等同于JavaScript 的||
  • 数字,完全错误的问题,但可能对其他人有用。如果您知道我的新问题的答案 - 请随时详细说明。我必须等待 90 分钟才能提出新问题。
  • name = (a.nil? || a.empty? || a.zero?) ? 'bear' : a?
猜你喜欢
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 2011-09-17
相关资源
最近更新 更多