如何将 Ruby 中的两个字符串与 gets.chomp 分开?

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

我试着分开两个字符串。这是代码:

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

我不断收到此错误:

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

不能除一个string,你需要把它转换成一个int,即:

stone = lbs.to_i / stconversion.to_i

或将 string 转换为 float:

stone = lbs.to_f / stconversion.to_f

命令gets代表"get a string"。您正在尝试将字符串除以数字。

换行

lbs = gets.chomp

lbs = gets.chomp.to_i

将字符串转换为整数,或者如果您更喜欢使用浮点数,请使用 to_f

当您可以简单地利用 lbs = gets.to_i 时,利用 lbs = gets.chomp.to_i 就太过分了。这是处理它的正确方法。

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