secret
Last active

  • Download Gist
00 README.md
Markdown

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
01 Gemfile
1 2 3
source 'https://rubygems.org'
gem 'activerecord'
gem 'sqlite3'
02 gpa.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.