Calculate average of column value in Ruby on Rails

I'm kind of new to Ruby on Rails. I have a profile model which has_many courses taken.

create_table "profiles", force: :cascade do |t| t.string "pname" t.float "current_gpa"
end

and

create_table "courses", force: :cascade do |t| t.integer "course_number" t.float "gpa"
end

I want to calculate the average gpa: current_gpa = sum of gpa of courses taken / num of course taken. How can I do this?

1

3 Answers

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

An additional note here... Average returns floating point numbers or BigDecimal which is often represented in decimal notation. This can be confusing and may not be what you are looking for. You might explore adding something like: .to_int, .to_f, .truncate, .round, etc...

Person.average(:age) # => 0.387e2
Person.average(:age).to_i # => 38
Person.average(:age).to_f # => 38.7
Person.average(:age).to_f.round # => 39

You can use ActiveRecord::Calculations average:

profile.courses.average(:gpa)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like