Answer the question
In order to leave comments, you need to log in
How to get an array of dates with specific values in Rails?
I've been trying to figure this out for a few days now, but I can't figure it out.
Essence of the question:
There is an array of the form [{"yyyy-mm-dd": 2}, {"yyyy-mm-dd": 6}], that is, the content is a set of hashes with dates as keys and numbers as values.
What I'm trying to get: an array that lists all dates for the past year (1.year.ago..Date.today) as keys with values from the first array.
That is, let's say, the first array I have contains the following data:
"2014-05-31": 3 , "2014-06-01": 5
And the second array has 365 hashes, the keys in which are the dates of each day of the year . The values are substituted from the first array and as a result I should get an array like
"2014-05-29": 0, ""2014-05-31": 3 , "2014-06-01": 5 , "2014-06-02": 0
Bold indicates the data of the first array, substituted into the second one.
Please tell me how can I do something like this? I've tried running through an if-elsif-else nested within another if-elsif-else, but I end up with an array of dates that only contains the last value.
I hope I explained it clearly enough, if not, I will try to clarify, just ask.
Answer the question
In order to leave comments, you need to log in
Not very pretty, but what do you need?
a = [{"2014-05-31" => 3}, {"2014-06-01" => 5}]
b = [{"2014-05-29" => 0}, {"2014-05-30" => 0}, {"2014-05-31" => 0}, {"2014-06-01" => 0}, {"2014-06-02" => 0}]
a.each {|c| b.select {|s| s.keys.first == c.keys.first}.first[c.keys.first] = c.values.first}
You can do this:
if the data in array A is unique:
a = [{"yyyy-mm-dd" => 2}, {"yyyy-mm-dd" => 6}]
b = [{"2014-01-01" => 0} ... {"2014-12-31" => 0}]
ah = Hash[*a.map(&:to_a).flatten]
bh = Hash[*b.map(&:to_a).flatten]
result = bh.merge(ah).map{|k,v| {k => v}}
ah = {}.tap{ |out| a.each{ |h| h.each{ |k,v| (out[k]||=[]) << v } } }
bh = Hash[*b.map(&:to_a).flatten]
result = bh.merge(ah).map{|k,v| {k => v}}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question