[英]Ruby unless && statement
I have the following in my application_controller.rb 我在application_controller.rb中有以下内容
def layout
unless request.subdomain.empty? && current_user.nil?
self.class.layout 'admin'
end
end
It seems the code above it's not working. 看来它上面的代码不起作用。 But when I do the following, it does work.
但是,当我执行以下操作时,它确实有效。
def layout
unless request.subdomain.empty?
unless current_user.nil?
self.class.layout 'admin'
end
end
end
I would like to simplify the code by removing one unless statement. 我想通过删除一个除非声明来简化代码。 How could I do that?
我怎么能这样做?
unless something
is equivalent to if !something
. unless something
等同于if !something
。 In your case, that would be 在你的情况下,那将是
if !(request.subdomain.empty? && current_user.nil?)
However, you want 随你怎么便
if (!request.subdomain.empty? && !current_user.nil?)
Using boolean algebra (De Morgan rule), you can rewrite that to 使用布尔代数(De Morgan规则),您可以将其重写为
if !(request.subdomain.empty? || current_user.nil?)
Using unless
使用
unless
unless request.subdomain.empty? || current_user.nil?
If you want to set the layout to 'admin'
if the subdomain is not empty and the current user is not nil: 如果要将子域设置为
'admin'
如果子域不为空且当前用户不为 nil:
def layout
if !request.subdomain.empty? && !current_user.nil?
self.class.layout 'admin'
end
end
Change your logic to use if
statements and positive predicates, it will make the logic in your code much easier to understand: 更改逻辑以使用
if
语句和正谓词,它将使代码中的逻辑更容易理解:
def layout
if request.subdomain.present? && current_user
self.class.layout "admin"
end
end
Best practice is to avoid unless
except in the most trivial cases. unless
在最琐碎的情况下, unless
最佳做法是避免。
Use: 采用:
if (!request.subdomain.empty? && !current_user.nil?)
I never use unless
with anything that is more complex (contains or/and), it's just too hard to reason about a statement like that. unless
有更复杂的东西(包含或/和), unless
我永远不会使用它,因此很难推断出这样的陈述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.