Aymeric Bouzy aybbyk Aymeric Bouzy aybbyk - 4 months ago 8
Ruby Question

Ruby hash with dates as keys

When I do this request on my database :

users_count = User.select("date_trunc('day', created_at)").group("date_trunc('day', created_at)").count


I then have a hash with dates as keys :

# => {2016-07-29 00:00:00 UTC=>1, 2016-07-06 00:00:00 UTC=>1, 2016-07-07 00:00:00 UTC=>1, 2016-07-13 00:00:00 UTC=>2, 2016-07-04 00:00:00 UTC=>421, 2016-07-09 00:00:00 UTC=>3, 2016-07-08 00:00:00 UTC=>2, 2016-07-22 00:00:00 UTC=>1, 2016-07-19 00:00:00 UTC=>1, 2016-07-21 00:00:00 UTC=>2}


But then I'm not able to retrieve data by date :

date = DateTime.new(2016, 7, 29)
# => Fri, 29 Jul 2016
users_count[date]
# => nil
users_count.keys.first === date
# => true
users_count[users_count.keys.first]
# => 1


How can I retrieve the number of users created on specific days in a single request? And why is ruby giving me a value of nil for a key that is present in the hash?

Thanks for your help.

ruby version 2.2.4, Rails version 4.2.5.1

Answer

Use DateTime instance instead, converted to time, since hash keys are apparently instances of Time:

date = DateTime.new(2016,7,29,0,0,0).to_time