如何将变量打印回我的函数?

时间:2015-07-10 02:20:45

标签: ruby

我正在尝试通过gets.chomp添加用户输入的总成本,然后将其重新放入函数中,以便打印出函数末尾的总成本。我这样做对吗?

def costs_of_company(hosting, design, phones, total_costs)
  puts "Total costs are as follows: \n"
  puts "Hosting costs $#{hosting}."
  puts "Design would cost $#{design}."
  puts "The cost for 100 Phones would be $#{phones}."
  puts "Total costs are #{total_costs}"
end

puts "Tell me the costs of your company. \n"
puts "hosting \n"
hosting = gets.chomp
puts "design \n"
design = gets.chomp
puts "phones \n"
phones = gets.chomp
total_costs = hosting + design + phones  #I think i am way off here.

costs_of_company(hosting, design, phones)

2 个答案:

答案 0 :(得分:1)

total_costs = hosting.to_i + design.to_i + phones.to_i的问题是输入是字符串格式。如果您执行了.to_f

,这将有效

这假设所有输入都是整数。或者,如果要使用小数(浮点数),请使用hosting = gets.chomp.to_i

此外,您还可以执行design = gets.chomp.to_iphones = gets.chomp.to_i.to_i

然而,现在我们进入了一个领域,我们如何知道用户是否给了我们很好的输入?如果输入不是整数,则"hello".to_i == 0的默认行为默认为零,例如Integer()。这对大多数情况都很好。

更复杂的方法是创建一个处理用户输入的函数,以便您可以在一个地方清理所有内容,并处理错误。例如,如果您想使用.to_i而不是def get_input while true begin input = gets.chomp.match(/d+/)[0] rescue Exception => e puts "that is not a valid integer. Please try again" else return input end end end ,则需要捕获错误,因为对于带有整数的无效输入会抛出异常。下面是使用正则表达式通过异常处理来清理输入的示例。

.myimage { max-width: 100%; height: auto;}



@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 480px)
  and (orientation: portrait) {
}

答案 1 :(得分:0)

我会用.to_f来追踪美分并将它打印得更漂亮。这是一个调试版本:

def print_money(val)
  format('%.2f',val)
end

def costs_of_company(hosting, design, phones)
  puts "Total costs are as follows: \n"
  puts "Hosting costs $#{print_money(hosting)}."
  puts "Design would cost $#{print_money(design)}."
  puts "The cost for 100 Phones would be $#{print_money(phones)}."
  total_costs = hosting + design + phones
  puts "Total costs are $#{print_money(total_costs)}"
end

puts "Tell me the costs of your company. \n"
puts "hosting \n"
hosting = gets.chomp.to_f
puts "design \n"
design = gets.chomp.to_f
puts "phones \n"
phones = gets.chomp.to_f

costs_of_company(hosting, design, phones)