2013-12-08 32 views
0

我是Ruby的新手,我正在創建小預算幫手。簡化我的代碼與方法?

我知道有一種方法可以進一步簡化此代碼,而且我似乎無法將我的頭圍繞在需要創建的方法上。我不停地重複needswantssave五十,三十,二十,等:

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}" 
+0

這個問題更好的地方可能是[代碼評論](http://codereview.stackexchange.com)。 –

+0

Alrighty!謝謝。我一定會在下一次發佈。 –

+2

這個問題似乎是離題,因爲它似乎屬於codereview.stackexchange.com – kero

回答

3

你基本上要循環每類時間段,然後遍歷每個項目在範圍內的預算。這裏有一個簡單的方法,你可以完成它:

puts "What's your annual income?" 
annual_income = gets.to_i 

budget = { 
    :needs => 0.5, 
    :wants => 0.3, 
    :save => 0.2, 
} 

periods = { 
    'weekly' => 52.1775, 
    'monthly' => 12, 
    'yearly' => 1, 
} 

periods.each do |period_name, periods_per_year| 
    budget.each do |line_item_name, line_item_fraction| 
    amount = annual_income.to_f/periods_per_year * line_item_fraction 
    puts "You should spend %0.2f on '%s' %s" % [amount, line_item_name, period_name] 
    end 
end 

輸出是不完全一樣的你,但它的作品。這裏是我得到的,如果我輸入1000:

You should spend 9.58 on 'needs' weekly 
You should spend 5.75 on 'wants' weekly 
You should spend 3.83 on 'save' weekly 
You should spend 41.67 on 'needs' monthly 
You should spend 25.00 on 'wants' monthly 
You should spend 16.67 on 'save' monthly 
You should spend 500.00 on 'needs' yearly 
You should spend 300.00 on 'wants' yearly 
You should spend 200.00 on 'save' yearly 
+0

完美!這足以讓我使用它如何工作的想法。 –

+1

+1,很好地完成。除了優秀的重構之外,使用String的'%'代替傳統的'sprintf'是慣用的Ruby。我看到你錯過的唯一的東西是在值前面使用美元符號,但是可以將其分配給常量,然後替換爲格式字符串,從而允許代碼適用於任何貨幣並進行小小的調整。 –