【问题标题】:utility method like ActiveSupport#try in ruby that returns a default value if method undefined实用方法,如 ruby​​ 中的 ActiveSupport#try,如果方法未定义,则返回默认值
【发布时间】:2016-04-06 21:06:37
【问题描述】:

我有时会使用ActiveSupport中的#try

1.try(:not_a_method)
#=> nil

耶!没有抛出异常,但假设我不想要 nil:

1.better_than_try(:not_a_method){0}
#=> 0

这存在吗?

【问题讨论】:

  • 您始终可以编写自己的核心扩展,称为try_or_whatever

标签: ruby activesupport


【解决方案1】:

当你想返回一些东西而不是nil时,你可以使用||操作符:

1.try(:not_a_method) || 0
#=> 0

【讨论】:

  • 这里的一个警告是这将践踏false 值和任何合法返回nil 的方法。
猜你喜欢
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-12
相关资源
最近更新 更多