干红宝石三元 [英] DRY up Ruby ternary

查看:86
本文介绍了干红宝石三元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到一种情况,我想做一些条件逻辑,然后返回一部分条件。如何在不重复部分真假表达式的情况下做到这一点?

I often have a situation where I want to do some conditional logic and then return a part of the condition. How can I do this without repeating the part of the condition in the true or false expression?

例如:

ClassName.method.blank? ? false : ClassName.method

有什么方法可以避免重复 ClassName.method

Is there any way to avoid repeating ClassName.method?

这是一个真实的示例:

PROFESSIONAL_ROLES.key(self.professional_role).nil? ? 
    948460516 : PROFESSIONAL_ROLES.key(self.professional_role)


推荐答案

假设您可以接受 false nil 相同的对待,则使用 ||

Assuming you're okay with false being treated the same way as nil, you use ||:

PROFESSIONAL_ROLES.key(self.professional_role) || 948460516

如果<$,将返回 948460516 c $ c> key 返回 nil false 并返回调用的值 key 否则。

This will return 948460516 if key returns nil or false and the return value of the call to key otherwise.

请注意,如果 key 返回 nil false ,而不是返回空数组或字符串。由于您在第二个示例中使用了 nil?,因此我认为可以。但是,在第一个示例中,您使用了 blank?(并且 blank?返回 true 用于空数组和字符串),所以我不确定。

Note that this will only return 948460516 if key returns nil or false, not if it returns an empty array or string. Since you used nil? in your second example, I assume that's okay. However you used blank? in the first example (and blank? returns true for empty arrays and strings), so I'm not sure.

这篇关于干红宝石三元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆