首页 > 解决方案 > 基于 1 个对象检查 2 个条件的更好方法

问题描述

我通常需要使用这种方法来检查对象是否存在以及该对象是否返回特定值或行为。这是编写此代码的更好方法吗?

def set_current_theme
   if current_tenant && current_tenant.has_custom_domain?
     @theme = Theme.last || Theme.create
   end
end

乍一看,我只想添加一个条件:这就if current_tenant.has_custom_domain?足够了。但结果通常是 nil 类没有这样的方法(在这种情况下has_custom_domain?)。

标签: ruby-on-railsruby

解决方案


更短(我认为更好)的方法是像这样使用&.(它的简写try!)。

if current_tenant&.has_custom_domain?
  @theme = Theme.last || Theme.create
end

& 是什么意思。(& 点)在 Ruby 中是什么意思?


推荐阅读