0

我有一个这样的哈希数组,按以下值排序:a

[{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]

我怎样才能得到这个数组的一个子集,它的哈希值是最小值:a?在这里,最小值:a0,所以我需要:

[{:a=>0, :b=>10}, {:a=>0, :b=>35}]
4

2 回答 2

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]}
于 2012-09-17T01:59:40.897 回答
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}]
于 2012-09-17T08:48:09.137 回答