Find average date from collection of dates (Ruby)
I have a table of guesses, within each guess is just a date. I was wondering how I would go about turning 开发者_运维技巧two or more dates into an average.
<div id="logic">
<% foo = Date.today %>
<% bar = Date.today + 10 %>
<%= (foo + bar) / 2 %>
Something like this, but obviously Ruby won't let me divide the two dates.
Date is a bit hard to work with, you should use Time. Try converting the Dates into Times:
require 'time'
foo_time = Time.parse(foo.to_s)
bar_time = Time.parse(bar.to_s)
Convert them to timestamps, then calculate the average, then convert back to Time:
avg = Time.at((foo_time.to_f + bar_time.to_f) / 2)
You can convert that back to Date:
avg_date = Date.parse(avg.to_s)
to_time.to_i
Is my friend ;)
精彩评论