Reputation: 173
I'm trying to add the total costs of a users input via gets.chomp and then put that back into the function so it prints outs the total costs at the end of the function. Am i doing this right?
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)
Upvotes: 1
Views: 41
Reputation: 2761
The problem with the line total_costs = hosting + design + phones
is that input is in String format. That would work if you did total_costs = hosting.to_i + design.to_i + phones.to_i
This is assuming all inputs are integers. Alternatively, use .to_f
if you want to use decimals (floats).
Furthermore, you can also do hosting = gets.chomp.to_i
, design = gets.chomp.to_i
, and phones = gets.chomp.to_i
However, now we enter the realm of how do we know if the user gave us good input? The default behavior of .to_i
is to default to zero if the input is not an integer e.g. "hello".to_i == 0
. This is fine for most cases.
A more sophisticated approach would be to make a function that handles the user input so that you can sanitize everything in one place, AND handle errors. For example if you wanted to use Integer()
instead of .to_i
you would need to catch errors because an exception is thrown for invalid input with integer. Here is an example of using a regular expression to sanitize the input with exception handling.
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
Upvotes: 1
Reputation: 885
I would use .to_f for money to keep track of cents and print it a bit prettier. Here's a debugged version:
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)
Upvotes: 0