【发布时间】:2014-06-12 16:53:43
【问题描述】:
我有一个称为间隔的数组。我希望从中构建一个哈希数组,为每个哈希添加两个键/值对(start_ts 和 stop_ts)。
require 'date'
date = '2014-06-12'
totalhash = Hash.new
totalarray = Array.new
payload2 = Array.new
totals = Array.new
intervals = [["Current", 0, 9999],
["1 to 4", -4, -1],
["5 to 15", -15, -5],
["16 to 30", -30, -16],
["31 to 60", -60, -31],
["61 to 90", -90, -61],
["91+", -9999, -91]]
intervals.each do |int|
label, start, stop = int
# Parse date and then convert to UNIX epoch (.to_time.to_i chain)
start_ts = (Date.parse("#{date}") + start).to_time.to_i
stop_ts = (Date.parse("#{date}") + stop).to_time.to_i
totalhash[:label] = label
totalhash[:start] = start
totalhash[:stop] = stop
totalhash[:start_ts] = start_ts
totalhash[:stop_ts] = stop_ts
totalarray << totalhash
totals = totalarray.reduce Hash.new, :merge
puts totals
puts 'totals size: ' + totals.size.to_s
end
最终结果应该是一个由七个哈希组成的数组。目前,数组 totalarray 似乎在每次传递时都会被覆盖,而不是被附加到。
我做错了什么。谢谢。
【问题讨论】:
-
你是如何运行这段代码的?它有太多语法错误..
-
@ArupRakshit 我只看到一个语法错误:
intervals.each do |int| do(do两次)。 -
我添加了 require 'date' 并删除了有问题的第二个 do。对此感到抱歉。
-
@Jordan 如果你运行,你会得到另一个,使用 OP 之前的代码。但在那之后,我没有运行它..
-
您能解释一下
totals的含义吗?