Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

example usage

$ bundle install
$ irb
>> require "./gpa"
-- create_table(:courses)
   -> 0.0088s
-- create_table(:students)
   -> 0.0007s
=> true

>> susan = Student.create! name: "Susan"
=> #<Student id: 2, name: "Susan">

>> susan.courses.create! name: "Underwater Basket Weaving", grade_points: 4, credit_hours: 3
=> #<Course id: 3, student_id: 2, name: "Underwater Basket Weaving", grade_points: #<BigDecimal:102824b70,'0.4E1',9(36)>, credit_hours: #<BigDecimal:102824aa8,'0.3E1',9(36)>>

>> susan.courses.create! name: "Quantum Physics", grade_points: 0, credit_hours: 4
=> #<Course id: 4, student_id: 2, name: "Quantum Physics", grade_points: #<BigDecimal:10283c798,'0.0',9(36)>, credit_hours: <BigDecimal:10283c6d0,'0.4E1',9(36)>>

>> puts susan.calculate_gpa
0.571428571428571429
#=> nil
source 'https://rubygems.org'
gem 'activerecord'
gem 'sqlite3'
require 'bundler/setup'
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Schema.define do
create_table :courses do |t|
t.belongs_to :student
t.string :name
t.decimal :grade_points
t.decimal :credit_hours
end
create_table :students do |t|
t.string :name
end
end
class Course < ActiveRecord::Base
belongs_to :student
validates :grade_points, :credit_hours, presence: true, numericality: true
end
class Student < ActiveRecord::Base
has_many :courses
def calculate_gpa
courses.sum(:grade_points) / courses.sum(:credit_hours)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.