Ruby 如何将变量打印回函数中?
我试图通过gets.chomp添加用户输入的总成本,然后将其放回函数中,以便它在函数末尾打印出总成本。我这样做对吗Ruby 如何将变量打印回函数中?,ruby,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 f
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)
行
total_costs=hosting+design+phones
的问题在于输入是字符串格式的。如果你做了total_costs=hosting.to_i+design.to_i+phones.to_i
这是假设所有输入都是整数。或者,如果要使用小数(浮点数),请使用.to_f
此外,您还可以执行hosting=gets.chomp.to_i
,design=gets.chomp.to_i
,以及phones=gets.chomp.to_i
然而,现在我们进入了如何知道用户是否给了我们好的输入的领域?如果输入不是整数,则.to_i
的默认行为默认为零,例如“hello”。to_i==0
。这在大多数情况下都很好
一种更复杂的方法是创建一个处理用户输入的函数,这样您就可以在一个地方清理所有内容并处理错误。例如,如果要使用Integer()
而不是,则需要捕获错误,因为使用Integer的无效输入会引发异常。下面是一个使用正则表达式通过异常处理清理输入的示例
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
我会使用.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)
我相信您忘了在最后一行将total_costs
变量传递给公司的costs_
函数调用def print_money(val)格式('.2f',val)结束此函数中发生的事情。%。2f这个数字是浮动的吗?非常感谢您的深入分析。我会研究你概述的东西,然后继续前进。没问题!如果这是您要查找的答案,请确保单击投票箭头下的复选标记。