我有一个像这样的哈希数组,它按:a
的值排序:
[{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
如何获取具有:a
最小值的哈希值的此数组的子集?
此处,:a
的最小值为0
,因此我需要:
[{:a=>0, :b=>10}, {:a=>0, :b=>35}]
答案 0 :(得分:3)
z = [{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
z.select{|y| y[:a] == z.first[:a]}
答案 1 :(得分:1)
对我而言,似乎接受的答案假设数组中第一个元素的:a
值是最小值。因此,如果在第一个元素中:a => 1
处修改了数组,则结果不正确。这是一个例子:
# original
z = [{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
puts z.select{|y| y[:a] == z.first[:a]}.inspect
# => [{:a=>0, :b=>10}, {:a=>0, :b=>35}] the result is the expected one
# modified :a of first element
z = [{:a=>1, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
puts z.select{|y| y[:a] == z.first[:a]}.inspect
# => [{:a=>1, :b=>10}, {:a=>1, :b=>20}] here result does not have min :a
现在,没有做出这个假设我正在采取额外的步骤来找到:a
的最小值
z = [{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
# find the min :a
m = z.map { |y| y[:a] }.min
puts z.select{|y| y[:a] == m}.inspect
# => [{:a=>0, :b=>10}, {:a=>0, :b=>35}]
# modified :a of first element
z = [{:a=>1, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
m = z.map { |y| y[:a] }.min
puts z.select{|y| y[:a] == m}.inspect
# => [{:a=>0, :b=>35}]