Find average date from collection of dates (Ruby)
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)
Calculate average number of days between datetimes in Ruby
I think you have an off-by-one problem. If you have n
values in dates
then you'll have n-1
differences between consecutive pairs so your avg
should be:
avg = difference.inject{ |sum, el| sum + el }.to_f / (arr.size - 1)
And your inject
is just a long winded way of saying inject(:+)
so you could say:
avg = difference.inject(:+).to_f / (arr.size - 1)
In any case, you could use map
and each_cons
to make it a bit nicer:
dates.map(&:to_date).each_cons(2).map { |d1, d2| d1 - d2 }.inject(:+) / (dates.length - 1)
First we can convert everything to dates in one pass with map(&:to_date)
rather than converting every time we need a date instead of a string. Then the each_cons(2)
iterates over the array in consecutive pairs (i.e. [1,2,3,4]
is iterated as [[1,2], [2,3], [3,4]]
). Then a simple map
to get the differences between the pairs and inject(:+)
to add them all up.
The above will leave you with a Rational
but you can to_f
or to_i
that if you need a floating point or integer value.
Calculating the average days between records in Rails
The maximum
and minimum
class methods of your model will use the SQL aggregate functions min()
and max()
to find the extreme values efficiently.
span_secs = Foo.maximum(:created_at) - Foo.minimum(:created_at)
avg_secs = span_secs / (Foo.count - 1)
avg_days = avg_secs / (24 * 60 * 60)
Rails calculate and display average
Together with other calculations, ActiveRecord provides a method called average. You can use it by implementing something like this:
class Movie
def self.average_by_genre(genre)
average(:rating).where(:genre => genre)
end
end
Alternatively, you can also implement it as an instance method of the Movie model.
class Movie
def average_rating
self.class.average(:rating).where(:genre => self.genre)
end
end
This would let you call the method directly from your view.
<article>
<header>
<h1><%= @movie.title %></h1>
</header>
<p>
<span>Average rating for genre <%= @movie.genre %>:</span>
<%= @movie.average_rating %>
</p>
</article>
ruby on rails average per day
Try using
Date.today.at_beginning_of_month.to_s(:db)
and
Date.today.tomorrow.to_s(:db)
instead.
Calculate average of column value in Ruby on Rails
You should consider reading some documentation - obviously it's quick to get a answer on SO but sometimes the docs can lead you to something you didn't know to look for or ask for.
That said, the fastest way is to use average
profile.courses.average(:gpa)
This will give you an average. Or you can do it the long way, if for some reason you need make modifications in between.
profile.courses.sum(:gpa) / profile.courses.count
Average of group by date records in Elasticsearch
I got the average by following
average_properties_by_date:{
avg_bucket: {
buckets_path: 'group_by_date>_count',
gap_policy: "skip",
format: "#,##0.00;(#,##0.00)"
}
}
Be careful here _count will be used instead of doc_count.
Related Topics
I Want to Return a Single Result Using .Find() with Ruby on Rails
How to Sort a Ruby Array by Two Conditions
Does Ruby Provide a Constant_Added Hook Method
How to Display Error Messages in a Multi-Model Form with Transaction
How to Display a Link to Individual Microposts? (Ruby on Rails 3)
Assets Precompiling Error with Jquery UI Plugin
Error Loading the 'Sqlite3' Active Record Adapter. When I Deploy in Heroku
How to Condense Summable Metrics to a Unique Identifier in a Ruby Table
How to Use 'Debugger' and 'Pry' When Developing a Gem? (Ruby)
How to Escape All Characters with Special Meaning in Regex
On Destroying Session via Devise "Couldn't Find User with 'Id'=Sign_Out"
Rspec: How to Write Unit Test Case to Receive an Exception Which Is Getting Raised in Private Method
Rails Activerecord: Saving Nested Models Is Rolled Back
Ruby/Rails - Active Record Db Migration to MySQL - Timestamp Type