访问嵌套哈希中的第一个和最后一个元素

时间:2017-04-09 15:49:41

标签: ruby-on-rails ruby multidimensional-array hashmap

我每个月都使用group_by来对energy_delta列进行分组,所以这里是group_by方法的结果

{
  "2017-04-01 00:00:00 UTC": [
    {
      "id": null,
      "created_at": "2017-04-01T02:14:19.870Z",
      "energy_delta": 1
    },
    {
      "id": null,
      "created_at": "2017-04-01T02:14:19.979Z",
      "energy_delta": 3
    },
    {
      "id": null,
      "created_at": "2017-04-04T15:00:01.136Z",
      "energy_delta": 10
    }
],
 "2017-01-01 00:00:00 UTC": [
    {
      "id": null,
      "created_at": "2017-01-31T02:14:21.300Z",
      "energy_delta": 167
    },
    {
      "id": null,
      "created_at": "2017-01-31T02:14:21.311Z",
      "energy_delta": 184
    },
    {
      "id": null,
      "created_at": "2017-01-30T02:14:21.322Z",
      "energy_delta": 200
    }
]}

现在我有了这个嵌套哈希,我希望每个月从第一个energy_delta中减去最后一个energy_delta。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

鉴于您已将输入存储为input中的哈希值,您可以执行以下操作:

input.collect { |month, entries| { month => entries.first[:energy_delta] - entries.last[:energy_delta] } }

答案 1 :(得分:0)

如果您的读数已按日期排序,则可以使用:

grouped_by_month.each do |month, readings|
  first_value = readings.first[:energy_delta]
  last_value  = readings.last[:energy_delta]
  puts month
  puts last_value - first_value
end

输出:

2017-04-01 00:00:00 UTC
9
2017-01-01 00:00:00 UTC
33

如果您想按日期对它们进行排序,可以使用:

grouped_by_month.each do |month, readings|
  sorted_readings = readings.sort_by{ |reading| reading[:created_at] }
  first_value = sorted_readings.first[:energy_delta]
  last_value  = sorted_readings.last[:energy_delta]
  puts month
  puts last_value - first_value
end

输出:

2017-04-01 00:00:00 UTC
9
2017-01-01 00:00:00 UTC
-16