根据键的值将哈希数组拆分为两个

时间:2014-02-05 17:10:44

标签: ruby arrays

如何根据ate键的值将这个哈希数组拆分为两个?

array = [
  { name: "Gad", ate: true },
  { name: "Lad", ate: false },
  { name: "Bad", ate: true },
  { name: "Sad", ate: false }
]

示例输出

array_1 = [
  { name: "Gad", ate: true },
  { name: "Bad", ate: true }
]
array_2 = [
  { name: "Lad", ate: false },
  { name: "Sad", ate: false }
]

3 个答案:

答案 0 :(得分:14)

使用Enumerable#partition方法:

array.partition { |x| x[:ate] }
# => [[{:name=>"Gad", :ate=>true}, {:name=>"Bad", :ate=>true}], 
#     [{:name=>"Lad", :ate=>false}, {:name=>"Sad", :ate=>false}]]

或者:

array_1, array_2 = array.partition { |x| x[:ate] }

array_1
# => [{:name=>"Gad", :ate=>true}, {:name=>"Bad", :ate=>true}]

array_2
# => [{:name=>"Lad", :ate=>false}, {:name=>"Sad", :ate=>false}]

答案 1 :(得分:2)

array_one, array_two = *array.group_by { |x| x[:ate] }.map(&:last)

=> array_one
=> # [{:name=>"Gad", :ate=>true}, {:name=>"Bad", :ate=>true}]
=> array_two
=> # [{:name=>"Lad", :ate=>false}, {:name=>"Sad", :ate=>false}]

thx @CarySwoveland

答案 2 :(得分:2)

我无法与partition竞争,但这是另一种方式:

trues  = array.select { |h| h[:ate] }
falses = array - trues