![](/img/trans.png)
[英]How can I check if an object with specific property exists in a Ruby array
[英]How can i check if a value exists in an array?
我正在 Rails 中建立一个状态网页,但我遇到了一个小问题。
我想检查一个数组是否包含“状态:假”。 如果这是真的,那么就会出现危险警报。
我已经有了一个解决方案,但我知道它应该 go 带有更“苗条”的代码。 这是已经有效的:
checkresults.map { |c| c.status }.include?(false)
=> true
这是检查结果的输入
checkresults = [Checkresult.new(status: false), Checkresult.new(status: true)
我试过的是
checkresults.include?(status: false)
我想要的 output 是“真”,但由于某种原因我得到“假”。
仅对数组使用一种方法如何工作?
你可以用any?
:
checkresults.any? { |r| !r.status }
这将为您返回true
或false
。
你可以使用:
checkresults.map(&:status).include?(false)
除了使用的符号外,这不会改变您当前代码的任何内容。 然而,这不是最快的解决方案。 由于您必须迭代整个数组,将当前元素映射到其状态。 然后检查值false
是否包含在数组中。
使用all?
, any?
还是none?
短路并在条件失败时立即停止迭代(在all?
或none?
)或在满足条件时(在any?
)。
你可以使用Enumerable#any? 或可枚举#all?
# sample: any?
[true, true].any? { |flag| flag == false } #=> false
[true, false].any? { |flag| flag == false } #=> true
# sample: all?
[true, true].all? { |flag| flag == true } #=> true
[true, false].all? { |flag| flag == true } #=> false
您可以使用其中任何一个
check_results.any? { |flag| flag == false }
!check_results.all? { |flag| flag == false }
让我们测试一下
class CheckResult
attr_reader :status
def initialize(status: flag)
@status = status
end
end
# expect_true
check_results = [CheckResult.new(status: false), CheckResult.new(status: true)]
check_results.any? { |result| result.status == false } #=> true
!check_results.all? { |result| result.status == true } #=> true
# expect_false
check_results = [CheckResult.new(status: true), CheckResult.new(status: true)]
check_results.any? { |result| result.status == false } #=> false
!check_results.all? { |result| result.status == true } #=> false
# shorthands
check_results = [CheckResult.new(status: false), CheckResult.new(status: true)]
!check_results.all? { |result| result.status == true } #=> true
!check_results.all?(&:status) #=> true
如果 checkresults 对象响应status
:
!checkresults.all?(&:status)
如果想再检查一个属性列,可以使用 Pluck。
使用#pluck作为 select 一个或多个属性的快捷方式,无需加载一堆记录来获取您想要的属性。
CheckResult.pluck(:status1, status2).include?(false)
检查两列将返回真或假。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.