如何过滤一组哈希图

时间:2014-05-01 04:56:42

标签: ruby

我有一个数组的哈希映射,表示颜色,每种颜色的阴影以及每个阴影的可用性

[
 {"color"=>"red", "shades"=>[]}, 
 {"color"=>"yellow", "shades"=>[]}, 
 {"name"=>"Pink", "shades"=>[{"name"=>"lightpink", "available"=>0}]}, 
 {"name"=>"Green", "shades"=>[{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1},    
    {"name"=>"lightergreen", "available"=>0}]}
}

从这个数组我想用available == 1

获取所有阴影

所以最后我想要这个:

[ {"name"=>"darkgreen", "available"=>1},
  {"name"=>"lightgreen", "available"=>1}
]

我怎么能得到它?

我尝试了这个,但它没有工作:

available_shades = []
all_shades = []
allcolors.each do |color|
  all_shades << color["shades"]
end

available_shades = all_shades.find{|shade| shade["available"] == 1}

2 个答案:

答案 0 :(得分:2)

您可以使用Array#select

array = [
 {"color"=>"red", "shades"=>[]}, 
 {"color"=>"yellow", "shades"=>[]}, 
 {"name"=>"Pink", "shades"=>[{"name"=>"lightpink", "available"=>0}]}, 
 {"name"=>"Green", "shades"=>[{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1},    
    {"name"=>"lightergreen", "available"=>0}]}
]

array.flat_map { |x| x["shades"] }.select { |x| x["available"] == 1 }
#=> [
#=>   {"name"=>"darkgreen", "available"=>1},
#=>   {"name"=>"lightgreen", "available"=>1}
#=> ]

答案 1 :(得分:1)

可以这样做: -

array = [
 {"color"=>"red", "shades"=>[]}, 
 {"color"=>"yellow", "shades"=>[]}, 
 {"name"=>"Pink", "shades"=>[{"name"=>"lightpink", "available"=>0}]}, 
 {"name"=>"Green", "shades"=>[{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1},    
    {"name"=>"lightergreen", "available"=>0}]}
]
ary = array.flat_map do |x| 
  x['shades'].select { |h| h['available'] == 1 } unless x['shades'].empty?
end.compact

ary # => [{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1}]