[英]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)
The command gets
stands for "get a string". 该命令gets
代表“得到一个字符串”。 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. 将字符串转换为整数,或者如果您更喜欢使用浮点数,则使用to_f
。
You cannot divide a string
, you need to convert it to an int
, ie: 您不能分割string
,需要将其转换为int
,即:
stone = lbs.to_i / stconversion.to_i
Or convert a string
to a float
: 或将string
转换为float
:
stone = lbs.to_f / stconversion.to_f
它在杀死利用lbs = gets.chomp.to_i
时,你可以简单地利用lbs = gets.to_i
这是处理它的正确方法。
puts "Enter a weight in lbs: " lbs = gets.to_i stconversion = 14 stone = lbs / stconversion puts "That is #{stone} stone"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.