我正在尝试创建一个函数来完成以下哈希中的小时序列.
{ name: "cardio",data: [["06:00",999],["09:00",154],["10:00",1059],["11:00",90]] }
它应该在字段数据中创建所有缺少的值
["07:00",0],["08:00",["12:00",["13:00",0] ... ["23:00",0]
预期结果:
{ name: "cardio",["07:00",90]],0] }
有可能吗?就像是:
data.each do |row| (6..23).each do |hour| ..... end end
解决方法
您可以使用
Array#assoc
来执行以下操作:
Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==.
input = { name: "cardio",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",["01:00",["02:00",["03:00",["04:00",["05:00",["06:00",90],["14:00",["15:00",["16:00",["17:00",["18:00",["19:00",["20:00",["21:00",["22:00",["23:00",0]]}