获取对象数组中具有最小值的哈希值

时间:2022-09-27 22:56:01

I have an array of hashes that look like this:

我有一系列哈希看起来像这样:

objects = [ {:area => -30}, {:area => 20}, {:area => 30}]

How would I get the hash which area is lower, but that is always bigger than 0?

我如何得到哪个区域较低的哈希值,但总是大于0?

I have tried this:

我试过这个:

objects.min_by { |el| (el[:area] if el[:area] > 0) }

But I guess that since (if...) returns NIL, it can't compare with the other values. How can I do that?

但我想因为(如果......)返回NIL,它无法与其他值进行比较。我怎样才能做到这一点?

4 个解决方案

#1


1  

objects = [ {:area => -30}, {:area => 20}, {:area => 30}]
objects.select{|h| h[:area] > 0}.min_by{|h| h[:area] }
# => {:area=>20}

#2


0  

I'd probably do this:

我可能会这样做:

objects.reject{|x| x[:area] <= 0}.min_by{|x| x[:area]}

#3


0  

I would use #inject that is providing you a sort of "map & reduce" feature.

我会使用#inject为你提供一种“map&reduce”功能。

objects = [ {:area => -30}, {:area => 20}, {:area => 30}]
objects.inject(nil) { |result, item| item[:area] > 0 && (result.nil? || item[:area] < result) ? item[:area] : result }
# => 20

You can simplify it by setting a value instead of nil as the first value (or a big value) and skipping the nil.

您可以通过设置值而不是nil作为第一个值(或一个大值)并跳过零来简化它。

objects = [ {:area => -30}, {:area => 20}, {:area => 30}]
objects.inject(objects[0][:area]) { |result, item| item[:area] > 0 && item[:area] < result ? item[:area] : result }
# => 20

#4


0  

You could use inject:

你可以使用注入:

objects.inject(nil) do |result, item|
  if item[:area] > 0 && (result.nil? || item[:area] < result[:area])
    item
  else
    result
  end
end

#1


1  

objects = [ {:area => -30}, {:area => 20}, {:area => 30}]
objects.select{|h| h[:area] > 0}.min_by{|h| h[:area] }
# => {:area=>20}

#2


0  

I'd probably do this:

我可能会这样做:

objects.reject{|x| x[:area] <= 0}.min_by{|x| x[:area]}

#3


0  

I would use #inject that is providing you a sort of "map & reduce" feature.

我会使用#inject为你提供一种“map&reduce”功能。

objects = [ {:area => -30}, {:area => 20}, {:area => 30}]
objects.inject(nil) { |result, item| item[:area] > 0 && (result.nil? || item[:area] < result) ? item[:area] : result }
# => 20

You can simplify it by setting a value instead of nil as the first value (or a big value) and skipping the nil.

您可以通过设置值而不是nil作为第一个值(或一个大值)并跳过零来简化它。

objects = [ {:area => -30}, {:area => 20}, {:area => 30}]
objects.inject(objects[0][:area]) { |result, item| item[:area] > 0 && item[:area] < result ? item[:area] : result }
# => 20

#4


0  

You could use inject:

你可以使用注入:

objects.inject(nil) do |result, item|
  if item[:area] > 0 && (result.nil? || item[:area] < result[:area])
    item
  else
    result
  end
end