简体   繁体   English

如何迭代具有最小属性的哈希和哈希数组

[英]How to iterate over array of hashes and hash with smallest attribute

I've got an array of hashes and I need to figure out which hash has the smallest height attributes. 我有一个哈希数组,我需要找出哪个哈希具有最小的height属性。 So given this array, 所以给定这个数组

[{"height"=>130, "source"=>"http.facebook.com/tiny_pic.jpg", "width"=>173},    
 {"height"=>1230, "source"=>"http.facebook.com/giant_pic.jpg", "width"=>1273}] 

I want to return this 我要退货

{"height"=>130, "source"=>"http.facebook.com/tiny_pic.jpg", "width"=>173}

What's the most efficient way to do this? 最有效的方法是什么?

确保它只是一个数组,所以:

array_of_hashes.min_by {|h| h['height']}

使用min方法:

hash = array.min { |a,b| a['height'] <=> b['height'] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM