简体   繁体   中英

Ruby date comparison in array

I have a ruby array end_dates that might look like...

end_dates =  [Sat, 14 Dec 2013, Sat, 14 Dec 2013, Sat, 14 Dec 2013, Fri, 13 Dec 2013, Sat, 14 Dec 2013, Sat, 14 Dec 2013, Sat, 14 Dec 2013]

...and I need a conditional statement that tells me weather a given date is greater than any of the dates in the array. So it might look like...

my_date = Thursday, 12 Dec 2013

compares my_date to all dates in the array and returns true if any dates are less than my_date

if my_date > end_dates
  do stuff
end

Not as efficient as using any? , but simpler:

if my_date > end_dates.min
  ...
end

If you keep the min value somewhere, and reuse it:

min = end_dates.min
...
if my_date > min
  ...
end

then it would not be inefficient.

if end_dates.any? { |end_date| end_date < my_date } # do stuff end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM