干燥 Ruby 三元
我经常遇到这样的情况:我想做一些条件逻辑,然后返回一部分条件。如何在不重复 true 或 false 表达式中的条件部分的情况下执行此操作?
例如:
ClassName.method.blank? ? false : ClassName.method
有没有办法避免重复ClassName.method
?
这是一个现实世界的例子:
PROFESSIONAL_ROLES.key(self.professional_role).nil? ?
948460516 : PROFESSIONAL_ROLES.key(self.professional_role)
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?
For example:
ClassName.method.blank? ? false : ClassName.method
Is there any way to avoid repeating ClassName.method
?
Here is a real-world example:
PROFESSIONAL_ROLES.key(self.professional_role).nil? ?
948460516 : PROFESSIONAL_ROLES.key(self.professional_role)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您同意将
false
视为与nil
相同的方式,则使用||
:这将返回
948460516
code> 如果key
返回nil
或false
,否则返回调用key
的返回值。请注意,如果
key
返回nil
或false
,则仅返回 948460516,而不是返回空数组或字符串。由于您在第二个示例中使用了nil?
,我认为这是可以的。但是,您在第一个示例中使用了blank?
(并且blank?
对于空数组和字符串返回true
),所以我不确定。Assuming you're okay with
false
being treated the same way asnil
, you use||
:This will return
948460516
ifkey
returnsnil
orfalse
and the return value of the call tokey
otherwise.Note that this will only return 948460516 if
key
returnsnil
orfalse
, not if it returns an empty array or string. Since you usednil?
in your second example, I assume that's okay. However you usedblank?
in the first example (andblank?
returnstrue
for empty arrays and strings), so I'm not sure.如果你只想 DRY,那么你可以使用临时变量:
如果你不想使用临时变量,你可以使用块:
对于你描述的情况(当你只想使用原始值时)默认检查失败),编写一个辅助方法很简单:
它与所描述的
||
方法非常相似,但也适用于您的blank?
例子。我通常使用临时变量来处理这类事情。
If you just want to DRY, then you can use a temp variable:
If you don't want to use a temp variable, you can use a block:
For the cases you describe (where you just want to use the original value when a default-check fails), it'd be straightforward to write a helper method:
which is very similar to the
||
method described, but would also work with yourblank?
example.I usually use temporary variables for this sort of thing.
我知道这看起来不太漂亮,但它确实让事情变得有点干燥。
如果您出于某种原因不想创建
temp
变量,则可以重用已存在的内容,例如$_
。I know this doesn't look too pretty, but it does make things a bit DRYer.
If you don't want to create
temp
variable for whatever reason, you could reuse something that already exists like$_
.