多键哈希的最大值

时间:2012-03-21 20:49:44

标签: ruby

这是我的哈希(在Json中) 我需要获得每个“高”值的最大值。例如,在这种情况下是16.94

如何在Ruby中获取它?

我尝试使用[] .max函数,但我不知道设置“关键字”来判断最大值

{
 "query": {
  "count": 124,
  "created": "2012-03-21T20:45:39Z",
  "lang": "en-US",
  "results": {
   "quote": [
    {
     "date": "2010-03-10",
     "Date": "2010-03-10",
     "Open": "16.51",
     "High": "16.94",
     "Low": "16.51",
     "Close": "16.79",
     "Volume": "33088600",
     "Adj_Close": "16.79"
    },
    {
     "date": "2010-03-09",
     "Date": "2010-03-09",
     "Open": "16.41",
     "High": "16.72",
     "Low": "16.40",
     "Close": "16.53",
     "Volume": "20755200",
     "Adj_Close": "16.53"
    },
    {
     "date": "2010-03-08",
     "Date": "2010-03-08",
     "Open": "16.32",
     "High": "16.61",
     "Low": "16.30",
     "Close": "16.52",
     "Volume": "30554000",
     "Adj_Close": "16.52"
    },
    {
     "date": "2010-03-05",
     "Date": "2010-03-05",
     "Open": "15.89",
     "High": "16.38",
     "Low": "15.89",
     "Close": "16.06",
     "Volume": "21415000",
     "Adj_Close": "16.06"
    }

2 个答案:

答案 0 :(得分:5)

假设quotes包含数组(在JSON解析之后),这是"quote"键的值,您可以使用max_by

quotes.max_by { |quote| quote["High"].to_f }["High"].to_f  #=> 16.94

或者您可以使用map& max

quotes.map { |quote| quote["High"].to_f }.max

答案 1 :(得分:0)

require 'yajl'
data = Yajl::Parser.parse json
data["query"]["results"]["quote"].max_by{|q| q["High"].to_f}
#=> {"date"=>"2010-03-10",
 "Date"=>"2010-03-10",
 "Open"=>"16.51",
 "High"=>"16.94",
 "Low"=>"16.51",
 "Close"=>"16.79",
 "Volume"=>"33088600",
 "Adj_Close"=>"16.79"}