I have this array:
@import = [{"User"=>[9], "Project"=>false, "Task"=>false, "Date"=>"2017-08-11", "Time (Hours)"=>2.0, "Comment"=>"Test 11"}, 1]
How do I find the keys which has the false value in the above array?
I have this array:
@import = [{"User"=>[9], "Project"=>false, "Task"=>false, "Date"=>"2017-08-11", "Time (Hours)"=>2.0, "Comment"=>"Test 11"}, 1]
How do I find the keys which has the false value in the above array?
You can use 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}
Other useful Hash methods: Ruby: Easiest Way to Filter Hash Keys?
You can use each_with_object
@import.first.each_with_object([]) do |(key, value), accu|
accu << key if value == false
end
or:
@import.first.select { |_key , value| value == false }.keys
Assuming that the structure of the array is always the same, you could do this:
@import.first.keys.select { |key| @import.first[key] == false }
#=> ["Project", "Task"]