ruby 中的 ActiveSupport#try 等实用方法 如果方法未定义,则 returns 默认值
utility method like ActiveSupport#try in ruby that returns a default value if method undefined
我有时使用 #try
从 ActiveSupport
:
1.try(:not_a_method)
#=> nil
耶!没有抛出异常,但假设我不想要 nil:
1.better_than_try(:not_a_method){0}
#=> 0
这个存在吗?
当你想要 return 而不是 nil
时,你可以使用 ||
运算符:
1.try(:not_a_method) || 0
#=> 0
我有时使用 #try
从 ActiveSupport
:
1.try(:not_a_method)
#=> nil
耶!没有抛出异常,但假设我不想要 nil:
1.better_than_try(:not_a_method){0}
#=> 0
这个存在吗?
当你想要 return 而不是 nil
时,你可以使用 ||
运算符:
1.try(:not_a_method) || 0
#=> 0