如何找到具有错误值的键?

时间:2017-08-07 14:22:30

标签: ruby-on-rails ruby ruby-on-rails-4

我有这个数组:

@import = [{"User"=>[9], "Project"=>false, "Task"=>false, "Date"=>"2017-08-11", "Time (Hours)"=>2.0, "Comment"=>"Test 11"}, 1]

如何在上面的数组中找到具有false值的键?

3 个答案:

答案 0 :(得分:3)

您可以使用Hash#select

hash = {"User"=>[9], "Project"=>false, "Task"=>false, "Date"=>"2017-08-11", "Time (Hours)"=>2.0, "Comment"=>"Test 11"}
hash.select { |k,v| v == false }
# => {"Project"=>false, "Task"=>false}

其他有用的哈希方法:Ruby: Easiest Way to Filter Hash Keys?

答案 1 :(得分:2)

您可以使用each_with_object

@import.first.each_with_object([]) do |(key, value), accu|
  accu << key if value == false
end

或:

@import.first.select { |_key , value| value == false }.keys

答案 2 :(得分:1)

假设数组的结构总是相同的,你可以这样做:

@import.first.keys.select { |key| @import.first[key] == false }
#=> ["Project", "Task"]