0

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)
Casey Robinson
  • 3,268
  • 2
  • 14
  • 21
Thomas
  • 25
  • 3

3 Answers3

3

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.

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
0r4cl3
  • 132
  • 8
2

You cannot divide a string, you need to convert it to an int, i.e.:

stone = lbs.to_i / stconversion.to_i

Or convert a string to a float:

stone = lbs.to_f / stconversion.to_f
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 2
    int ? What language is this? Also, this does integer division in ruby, 13/14 results in 0. – steenslag Oct 10 '15 at 19:36
  • You use `str.to_i`in ruby – pppery Oct 10 '15 at 19:37
  • 3
    @ppperry in this case `to_f`may be a better choice. – steenslag Oct 10 '15 at 19:38
  • 1
    Unless integer division is specifically requested, assume that a float is required, which you might then convert. Dependiing on requirements, that might be `lbs.to_f/stconversion`, `(lbs.to_f/stconversion).round(n)`, `(lbs.to_f/stconversion).floor` (or `to_i`) or `(lbs.to_f/stconversion).ceil`. – Cary Swoveland Oct 10 '15 at 20:31
  • @steenslag You're right. the reason I used `.to_i` is because the OP used the python `int` function instead of the `float` function. – pppery Oct 11 '15 at 13:30
0

Its over kill to utilize lbs = gets.chomp.to_i when you can simply utilize lbs = gets.to_i This is the proper way of handling it.

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

Casey Robinson
  • 3,268
  • 2
  • 14
  • 21