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



我正在使用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。我该怎么做?

假设您的输入在 input 中存储为哈希,您可以执行以下操作:

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

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

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

最新更新