我正在尝试创建一个函数来完成以下哈希中的小时序列。
{
name: "cardio",
data: [["06:00", 999], ["09:00", 154], ["10:00", 1059], ["11:00", 90]]
}
它应该在字段数据中创建所有缺失值
["07:00", 0], ["08:00", 0], ["12:00", 0], ["13:00", 0] ... ["23:00", 0]
预期结果:
{
name: "cardio",
data: [["06:00", 999], ["07:00", 0], ["08:00", 0], ["09:00", 154], ["10:00", 1059], ["11:00", 90]], ["12:00", 0], ["13:00", 0] ... ["23:00", 0]
}
有可能吗?类似的东西:
data.each do |row|
(6..23).each do |hour|
.....
end
end
答案 0 :(得分:8)
您可以使用Array#assoc
执行以下操作:
搜索一个数组,其元素也是使用obj。==将obj与每个包含数组的第一个元素进行比较的数组。
input = {
name: "cardio",
data: [["06:00", 999], ["09:00", 154], ["10:00", 1059], ["11:00", 90]]
}
input[:data] = 24.times.collect do |hour|
hour = "%02d:00" % hour
input[:data].assoc(hour) || [hour, 0]
end
puts input.inspect
# {:name=>"cardio", :data=>[["00:00", 0], ["01:00", 0], ["02:00", 0], ["03:00", 0], ["04:00", 0], ["05:00", 0], ["06:00", 999], ["07:00", 0], ["08:00", 0], ["09:00", 154], ["10:00", 1059], ["11:00", 90], ["12:00", 0], ["13:00", 0], ["14:00", 0], ["15:00", 0], ["16:00", 0], ["17:00", 0], ["18:00", 0], ["19:00", 0], ["20:00", 0], ["21:00", 0], ["22:00", 0], ["23:00", 0]]}
答案 1 :(得分:2)
数据
h = {name:"cardio", data:[["06:00", 999], ["09:00", 154], ["10:00", 1059], ["11:00", 90]]}
first = 7
last = 23
代码的
mdata = (first..last).each_with_object(h[:data].to_h) { |hour,g|
g["%02d:00" % hour] ||= 0 }.sort
#=> [["06:00", 999], ["07:00", 0], ["08:00", 0], ["09:00", 154], ["10:00", 1059],
# ["11:00", 90], ["12:00", 0],..., ["21:00", 0], ["23:00", 0]]
h.merge(h).merge(data: mdata)
#=> {:name=>"cardio",
# :data=>[["06:00", 999], ["07:00", 0], ["08:00", 0], ["09:00", 154],
# ["10:00", 1059], ["11:00", 90], ["12:00", 0],...["23:00", 0]]