Я новичок в Ruby, и я создаю небольшие бюджетные помощники.Упрощение моего кода с помощью методов?
Я знаю, что есть способ упростить этот код дальше, и я не могу окунуться в голову, какой метод мне нужно создать. Я повторяю needs
, wants
, save
и пятьдесят, тридцать, двадцать, и т.д .:
puts "What's your annual income?"
annual_income = gets.to_i
weeks = 52.1775
monthly_income = ((annual_income/weeks) * 2)
weekly_income = (annual_income/weeks)
needs = 0.5
wants = 0.3
save = 0.2
def calc_amount(income, expense)
sprintf('%.2f',(income * expense))
end
# Monthly
fifty_percent_monthly = calc_amount(monthly_income, needs)
puts "You should spend no more than $#{fifty_percent_monthly} on 'Needs' a month."
thirty_percent_monthly = calc_amount(monthly_income, wants)
puts "You should spend no more than $#{thirty_percent_monthly} on 'Wants' a month."
twenty_percent_monthly = calc_amount(monthly_income, save)
puts "You should save $#{twenty_percent_monthly} a month."
# Each paycheck
fifty_percent_weekly = calc_amount(weekly_income, needs)
puts "You should spend no more than $#{fifty_percent_weekly} on 'Needs' each paycheck."
thirty_percent_weekly = calc_amount(weekly_income, wants)
puts "You should spend no more than $#{thirty_percent_weekly} on 'Wants' each paycheck."
twenty_percent_weekly = calc_amount(weekly_income, save)
puts "You should save $#{twenty_percent_weekly} each paycheck."
# Total spent each year
yearly_needs = calc_amount(annual_income, needs)
puts "You'll be spending $#{yearly_needs} on 'Needs' each year."
yearly_wants = calc_amount(annual_income, wants)
puts "You'll be spending $#{yearly_wants} on 'Wants' each year."
yearly_savings = calc_amount(annual_income, save
puts "Congrats! Your total savings each year will be $#{yearly_savings}"
Лучшее место для этого вопроса, вероятно, [Обзор кодов] (http://codereview.stackexchange.com). –
Alrighty! Спасибо. Я обязательно отправлюсь туда в следующий раз. –
Этот вопрос, кажется, не по теме, потому что он, кажется, принадлежит на codereview.stackexchange.com – kero