How to create and fill in missing data by following a numerical sequence in a hash

I am trying to create a function to complete a clock sequence in the following hash.

{
  name: "cardio", 
  data: [["06:00", 999], ["09:00", 154], ["10:00", 1059], ["11:00", 90]]
}

It should create all the missing values ​​in the given fields.

["07:00", 0], ["08:00", 0], ["12:00", 0], ["13:00", 0] ... ["23:00", 0]

Expected Result:

{
 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]
}

Can this be done? Sort of:

data.each do |row|
 (6..23).each do |hour|
  .....
  end
end
+6
source share
2 answers

You can use Array#assocto do something like this:

Searches through an array whose elements are also arrays, comparing obj with the first element of each contained array using 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]]}
+8
source

Data

h = {name:"cardio", data:[["06:00", 999], ["09:00", 154], ["10:00", 1059], ["11:00", 90]]}
first =  7
last  = 23

code

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]]
+2
source

All Articles