Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate and fill the missing data following the numerical sequence in a hash

I'm trying to create a function to complete the sequence of hours 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 field data

["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]
}

Is it possible to do that? Something like:

data.each do |row|
 (6..23).each do |hour|
  .....
  end
end
like image 765
Bruno Fernandes Avatar asked Jul 21 '17 02:07

Bruno Fernandes


1 Answers

You can make use of Array#assoc to 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]]}
like image 111
Simple Lime Avatar answered Oct 19 '22 17:10

Simple Lime