我有一个这样的哈希数组,按以下值排序: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}]
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]}
在我看来,接受的答案似乎假设: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}]