从哈希数组导轨选择最大值 [英] rails select maximum value from array of hash

查看:124
本文介绍了从哈希数组导轨选择最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的散列的数组,我想利用这一最大值

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"}]

我要选择哈希数组的最大值,输出我要的是像数据:50.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'] }

任何帮助将是非常美联社preciated

any help will be very appreciated

推荐答案

有大量的在Ruby中这样做的方法。这里有两个。你可以传递给阵列#最大块如下:

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"

或者你可以使用阵列#地图来撕开:值输入了哈希:

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

请注意,您可能需要使用 #to_f 浮动(...)来避免做与字符串字符串比较,这取决于你的使用情况是什么。

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

这篇关于从哈希数组导轨选择最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆