Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get most recent date value from array of hashes

I have an array of hashes like this:

hashes = [{date: Date.today, value: 1},
          {date: Date.today - 1.day, value: 2},
          {date: Date.today - 2.day, value: 3},
          {date: Date.today + 1.day, value: 4}
]

And I want to get most recent date. I could get by:

hashes.sort{|i| i[:date]}.first[:date]
# => Sat, 27 Feb 2016

But I feel it's a bit redundant. Is there better way to implement this behavior?

like image 373
ironsand Avatar asked Oct 14 '25 11:10

ironsand


2 Answers

You can do it like:

hashes.max_by{|h| h[:date]}[:date]

or

hashes.map{|h| h[:date]}.max
like image 191
sawa Avatar answered Oct 17 '25 00:10

sawa


Ruby gives you .max and .min. So you always want to create the new date array and use ruby's methods:

date_array.min # => Oldest date
date_array.max # => Most recent date

As sawa's answer suggests: hashes.map{|h| h[:date]}.max is great. You use .map to create a new date array and use ruby function .max to determine the most recent date.

I see you are trying to use sort method but I would suggest you not to do so because sort is kind of wasteful when you only need the element to see if a computed value is largest or smallest.

FYI: http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-max_by

like image 21
Jefferson Avatar answered Oct 17 '25 00:10

Jefferson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!