[英]Ruby array.select multiline block
I am filtering an array in ruby and using a .select
block to do so.我正在过滤 ruby 中的数组并使用
.select
块来执行此操作。 The conditions are sufficiently complex that a single line block is hideous but not that large so a separate method seems like overkill.条件非常复杂,以至于单个行块是可怕的,但不是那么大,因此单独的方法似乎过大了。 Thus I want to use a multiline block.
因此我想使用多行块。 However I am unsure of the syntax.
但是我不确定语法。
filtered_array = base_array.select do |elem|
return false if condition1
return false if condition2
return true
end
The above is clearly incorrect as return
exits the method, not the block but gives an idea of what I am looking for.以上显然是不正确的,因为
return
退出了方法,而不是块,但给出了我在寻找什么的想法。
I could also use multiple select statements but that seems to obfuscate what I am trying to do.我也可以使用多个选择语句,但这似乎混淆了我想要做的事情。 Note that the above conditions are sufficiently complex that using logical operators to bind them results in a mess.
请注意,上述条件非常复杂,使用逻辑运算符绑定它们会导致混乱。
你想要的是next
而不是return
。
Edit: Just saw this: "using logical operators to bind them results in a mess."编辑:刚刚看到这个:“使用逻辑运算符绑定它们会导致混乱。” Could you provide the actual conditions?
能否提供实际情况?
filtered_array = base_array.select do |elem|
condition1 && condition2
end
You should probably just use:您可能应该只使用:
next(true)
However if that doesn't jive with you then do this:但是,如果这不适合您,请执行以下操作:
my_array.select do |x|
# bool = false ### optional, uncomment this if you prefer
if x.id == 1
bool = true
end
bool
end
Seems like this could be handled with a case statement:似乎可以使用 case 语句来处理:
filtered_array = base_array.select do |elem|
case
when condition1
false
when condition2
false
else
true
end
end
You can use next with unless combination till penultimate conditions您可以使用 next with unless 组合直到倒数第二个条件
filtered_array = base_array.select do |elem|
next unless condition1
condition2
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.