rails select maximum value from array of hash

独自空忆成欢 提交于 2019-12-23 14:58:01

问题


i have a array of hashes like this and i want to take the maximum value of that

data = [{name: "abc", value: "10.0"}, {name: "def", value: "15.0"}, {name: "ghi", value: "20.0"}, {name: "jkl", value: "50.0"}, {name: "mno", value: "30.0"}]

i want to select the maximum value of array of hashes, output i want is like data: "50.0"

how possible i do that, i've try this but it is seem doesnt work and just give me an error

data.select {|x| x.max['value'] }

any help will be very appreciated


回答1:


There are lots of ways of doing this in Ruby. Here are two. You could pass a block to Array#max as follows:

  > data.max { |a, b| a[:value] <=> b[:value] }[:value]
   => "50.0"

Or you could use Array#map to rip the :value entries out of the Hash:

  > data.map { |d| d[:value] }.max
   => "50.0"

Note that you might want to use #to_f or Float(...) to avoid doing String-String comparisons, depending on what your use case is.




回答2:


A shorter version of kranzky answer:

data.map(&:value).max



回答3:


You can also sort the array of hashes and get the values by index.

array = array.sort_by {|k| k[:value] }.reverse

puts array[0][:value]

Useful if you need minimum, second largest etc. too.



来源:https://stackoverflow.com/questions/27834879/rails-select-maximum-value-from-array-of-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!