返回哈希的前10个键值

时间:2012-10-29 09:25:20

标签: ruby

我正在读这样的JSON:

[
  {
    "Low": 8.63,
    "Volume": 14211900,
    "Date": "2012-10-26",
    "High": 8.79,
    "Close": 8.65,
    "Adj Close": 8.65,
    "Open": 8.7
  },
  {
    "Low": 8.65,
    "Volume": 12167500,
    "Date": "2012-10-25",
    "High": 8.81,
    "Close": 8.73,
    "Adj Close": 8.73,
    "Open": 8.76
  },
  {
    "Low": 8.68,
    "Volume": 20239700,
    "Date": "2012-10-24",
    "High": 8.92,
    "Close": 8.7,
    "Adj Close": 8.7,
    "Open": 8.85
  },
  {
    "Low": 8.78,
    "Volume": 23433900,
    "Date": "2012-10-23",
    "High": 8.94,
    "Close": 8.78,
    "Adj Close": 8.78,
    "Open": 8.93
  }
]

使用此:

json = File.read("#{symbols[0]}.json")

然后这样做:

result = JSON.parse(json)

然后,当我想为键值“Low”选择第一个值时,我这样做了:

puts result[0]['Low']

这返回58.75(正确)。

但我希望获得“低”的前三个值。我尝试执行以下操作,但它不起作用(表示无法将字符串转换为整数)。为什么?

puts result[0..2]['Low']

3 个答案:

答案 0 :(得分:1)

results = [
  {"Low"=>58.75, "Volume"=>163200, "Date"=>"1962-02-01", "High"=>59.63, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.63},
  {"Low"=>59.63, "Volume"=>134400, "Date"=>"1962-01-31", "High"=>60.0, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>59.88},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-26", "High"=>59.38, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.13},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-25", "High"=>59.88, "Close"=>59.13, "Adj Close"=>0.61, "Open"=>59.75},
  {"Low"=>58.5, "Volume"=>110400, "Date"=>"1962-01-24", "High"=>60.13, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>60.13}
]
results[0..2].collect {|element| element['Low']}
>> [58.75, 59.63, 59.13]

答案 1 :(得分:0)

假设你有哈希数组,你可以这样做:

results = [
  {"Low"=>58.75, "Volume"=>163200, "Date"=>"1962-02-01", "High"=>59.63, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.63},
  {"Low"=>59.63, "Volume"=>134400, "Date"=>"1962-01-31", "High"=>60.0, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>59.88},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-26", "High"=>59.38, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.13},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-25", "High"=>59.88, "Close"=>59.13, "Adj Close"=>0.61, "Open"=>59.75},
  {"Low"=>58.5, "Volume"=>110400, "Date"=>"1962-01-24", "High"=>60.13, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>60.13}
]

(0..2).map {|idx| results[idx]['Low']} # => [58.75, 59.63, 59.13]

答案 2 :(得分:0)

它不起作用的原因是

  • results[0]返回一个哈希值(然后您可以使用字符串['key']进行索引)
  • results[0..2]返回另一个(较小的)哈希数组(需要使用整数索引以获得单个哈希值)。

使用map功能(docs)可以获得您所追求的值。请注意,它的别名为collect,因此您可以使用您喜欢的任何内容。在这种情况下,您正在收集一组值,这可能是最合适的概念。

results[0..2].map {|hash| hash['Low']}
# or equivalently
results[0..2].collect {|hash| hash['Low']}