Ruby,由指定的散列键传递的散列数组

时间:2014-04-15 16:02:12

标签: ruby arrays hash key

我想通过指定为参数的传递哈希键对哈希数组进行排序:

array([{'a' => 2}, {'a' => 1}], 'a') => [{'a' => 1}, {'a' => 2}]]

array([{a: 1}, {a: 5}, {a: 3}], :a) => [{a:1}, {a: 3}, {a: 5}]

由于

1 个答案:

答案 0 :(得分:3)

def array(arr, key)
  arr.sort_by { |a| a[key] }
end