Search code examples
rubyinteger-division

How can I divide two strings in Ruby with gets.chomp?


I try to divide two strings. Here's the code:

puts "Enter a weight in lbs: "
lbs = gets.chomp
stconversion = 14
stone = lbs / stconversion
puts "That is #{stone} stone"

I keep getting this error:

/home/ubuntu/workspace/lbs to stones.rb:4:in `<main>': undefined method `/' for "14\n":String (NoMethodError)

Solution

  • The command gets stands for "get a string". You are trying to divide a string by a number.

    Change the line

    lbs = gets.chomp
    

    to

    lbs = gets.chomp.to_i
    

    to convert the string to an integer, or use to_f if you prefer using floats.