Last active
August 29, 2015 14:02
-
-
Save Murphydbuffalo/d4f2370400bf06c12c14 to your computer and use it in GitHub Desktop.
Solution to the mortgage calculator challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Mortgage | |
attr_reader :principal, :down_payment_percentage, :apr, :duration_in_years | |
def initialize(principal, down_payment_percentage, apr, years) | |
@principal = principal | |
@down_payment_percentage = down_payment_percentage | |
@apr = apr | |
@duration_in_years = years | |
end | |
def number_of_payments | |
duration_in_years * 12 | |
end | |
def down_payment | |
down_payment_percentage * principal | |
end | |
def monthly_rate_decimal | |
(apr/12) / 100 | |
end | |
def monthly_payment | |
# (monthly_rate_decimal * (principal - down_payment) ) / (1 - ((1 + monthly_rate_decimal) ** (-1 * number_of_payments)) ) | |
amount_owed / payment_coefficient #Both of these calculations yield the monthly payment | |
end | |
def amount_owed | |
( (1 + monthly_rate_decimal) ** number_of_payments ) * (principal - down_payment) | |
end | |
def payment_coefficient | |
counter = 1 | |
sum = 1 | |
(number_of_payments.to_i - 1).times do | |
sum += (1 + monthly_rate_decimal) ** counter | |
counter += 1 | |
end | |
sum | |
end | |
def principal_payment | |
(principal - down_payment) / number_of_payments | |
end | |
def total_interest_paid | |
(monthly_payment * number_of_payments) - principal | |
end | |
end | |
# require_relative 'mortgage' | |
DOWN_PAYMENT_PERCENTAGES = [0.05, 0.10, 0.15, 0.20] | |
print "What is the home value: " | |
home_value = gets.chomp.to_f | |
print "What is the APR: " | |
apr = gets.chomp.to_f | |
print "What is the duration (in years): " | |
duration_in_years = gets.chomp.to_f | |
puts | |
puts sprintf("%-15s %-10s %-10s %-20s %-20s", | |
"Down Payment", "Duration", "APR", "Monthly Payment", "Total Interest Paid") | |
DOWN_PAYMENT_PERCENTAGES.each do |down_payment_percentage| | |
mortgage = Mortgage.new(home_value, down_payment_percentage, apr, duration_in_years) | |
puts sprintf("%-15.2f %-10d %-10.3f %-20.2f %-20.2f", | |
mortgage.down_payment, duration_in_years, apr, | |
mortgage.monthly_payment, mortgage.total_interest_paid) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment