如何根据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 }
]

最佳答案

使用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}]

10-08 13:14