KnowledgeMC KnowledgeMC - 1 month ago 13
Ruby Question

Division in Ruby, error

it's my first day learning Ruby. I'm trying to write a Ruby program that asks the user for the cost of a meal and then what percentage they would like to tip and then does the calculation and prints out the result. I wrote the following:

puts "How much did your meal cost?"
cost = gets
puts "How much do you want to tip? (%)"
tip = gets
tip_total = cost * (tip/100.0)
puts "You should tip $" + tip_total


When I try to run it in Terminal, I get the following error message:

ip_calculator.rb:7:in `<main>': undefined method `/' for "20\n":String (NoMethodError)


I have no idea what this message means, can someone help me out understanding the error message and/or with what is wrong with my code? Thank you.

Answer

Becuse when you enter value from STDIN it's a String. And ruby can not divide String to 100.

Here is a working example:

#!/usr/bin/env ruby

puts "How much did your meal cost?"
cost = gets.to_f
puts "How much do you want to tip? (%)"
tip = gets.to_f
tip_total = cost * (tip/100.0)
puts "You should tip $ #{tip_total.round(2)}"

All entered values casted to Floats, do the calculations, and then print the rounded value.

[retgoat@iMac-Roman ~/temp]$ ./calc.rb
How much did your meal cost?
123.45
How much do you want to tip? (%)
12.43
You should tip $ 15.34