KnowledgeMC
KnowledgeMC

Reputation: 103

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.

Upvotes: 0

Views: 178

Answers (2)

Stefan
Stefan

Reputation: 114268

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

I have no idea what this message means

Let's break it down:

  • ip_calculator.rb the file the error occured in
  • 7 the line number (that's probably tip_total = cost * (tip/100.0))
  • <main> the class (main is Ruby's top-level class)
  • "undefined method `/' for "20\n":String" error message
  • NoMethodError exception class (http://ruby-doc.org/core/NoMethodError.html)

can someone help me out understanding the error message

The error message "undefined method `/' for "20\n":String" means, that you are attempting to call the method / on the object "20\n" which is a String and that this object doesn't implement such method:

"20\n" / 100
#=> NoMethodError: undefined method `/' for "20\n":String

what is wrong with my code?

Kernel#gets returns a string. gets doesn't attempt to interpret your input, it just passes the received characters. If you type 20return in your terminal, then gets returns a string containing the corresponding characters "2", "0", and "\n".

To convert the values, I'd use the built-in conversion methods Kernel#Integer or Kernel#Float:

cost = Float(gets)

Unlike to_i and to_f, these methods will raise an error if you enter a non-numeric value.

Upvotes: 3

retgoat
retgoat

Reputation: 2464

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

Upvotes: 1

Related Questions