Cameron Cameron - 2 months ago 10
Ruby Question

Get set of hashes from array of hashes between two date values

I have an array of hashes that contains a date and total key.

For example:

hash = [{
"Date"=>"01/01/2016",
"Total"=>10
},{
"Date"=>"02/01/2016",
"Total"=>20
},{
"Date"=>"03/01/2016",
"Total"=>30
},{
"Date"=>"04/01/2016",
"Total"=>40
},{
"Date"=>"05/01/2016",
"Total"=>50
}]


What I want to do is pass two dates to a method that then returns only hashes whose dates are either matching or between the two dates.

So for example:

get_data(startDate, endDate)

end


Where the startDate and endDate are '02/01/206' and
04/01/2016


Would return:

{
"Date"=>"02/01/2016",
"Total"=>20
},{
"Date"=>"03/01/2016",
"Total"=>30
},{
"Date"=>"04/01/2016",
"Total"=>40
}

Answer
def get_data(start_date, end_date, hash)
  hash.select{|entry| entry["Date"].to_date.between?(start_date.to_date, end_date.to_date) }
end
Comments