Calculate average number of days between dates in Ruby

I want to take a list of datetimes in Ruby, and then calculate the number of days between , and then average these dates. It's right? Is there a shorter way to do this?

dates = ["2012-08-05 00:00:00 UTC", "2012-06-17 00:00:00 UTC", "2012-06-15 00:00:00 UTC", "2011-06-06 00:00:00 UTC"]

difference = Array.new

dates.each_with_index do |date, index|
    if index != 0
        difference << date.to_date - dates[index - 1].to_date
    end
end

avg = difference.inject{ |sum, el| sum + el }.to_f / arr.size

And then it will output it in days format?

You can also tell me the version of Rails if you want, since I will be pulling time from the model field.

+4
source share
3 answers

I think you have a problem separately. If you have nvalues ​​in dates, then you will have n-1differences between consecutive pairs, so yours avgshould be:

avg = difference.inject{ |sum, el| sum + el }.to_f / (arr.size - 1)

inject - inject(:+), :

avg = difference.inject(:+).to_f / (arr.size - 1)

map each_cons, :

dates.map(&:to_date).each_cons(2).map { |d1, d2| d1 - d2 }.inject(:+) / (dates.length - 1)

map(&:to_date), , . each_cons(2) (.. [1,2,3,4] [[1,2], [2,3], [3,4]]). map, inject(:+), .

Rational, to_f to_i, .

+3

, , :

require 'date'
dates.map!{|x| Date.parse(x)}.sort!
p (dates.last - dates.first)/(dates.size - 1) #=> (142/1)

?

first, last = dates.map!{ |x| Date.parse(x) }.minmax
p (last - first)/(dates.size - 1) #=> (142/1)
+1

- :

def room_expiry_date_in_days(room)
 a=room.expiry_date.strftime("%Y-%m-%d")
 b=room.created_at.strftime("%Y-%m-%d")
 a=Date.parse(a)
 b=Date.parse(b)
 days=(a-b).to_i
 return  "#{pluralize(days, 'day',"days")} left"
end

, :

span_secs = Foo.maximum(:created_at) - Foo.minimum(:created_at)
avg_secs = span_secs / (Foo.count - 1)
avg_days = avg_secs / (24 * 60 * 60)

See: Calculating Average Days Between Rails Entries

0
source

Source: https://habr.com/ru/post/1524219/


All Articles