我是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