用方法简化我的代码?

时间:2013-12-08 00:24:31

标签: ruby-on-rails ruby

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

1 个答案:

答案 0 :(得分: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