Ruby 在简单程序上获取NoMethodError

Ruby 在简单程序上获取NoMethodError,ruby,Ruby,我是一个完全的Ruby新手,正在尝试编写一个简单的程序,将摄氏度转换为华氏度,反之亦然。 到目前为止,我的代码中的所有内容都正常工作,直到开始转换计算为止。 当它到达转换的第一行(摄氏到华氏的转换)时,我在终端中得到一个错误 test.rb:17:in:“45”的未定义方法“-”:字符串 (命名者) 有人能告诉我我缺少什么吗?我试着用谷歌搜索,但没用,可能只是因为我不确定自己在找什么。代码如下,提前感谢 puts "This program will convert temperatures f

我是一个完全的Ruby新手,正在尝试编写一个简单的程序,将摄氏度转换为华氏度,反之亦然。 到目前为止,我的代码中的所有内容都正常工作,直到开始转换计算为止。 当它到达转换的第一行(摄氏到华氏的转换)时,我在终端中得到一个错误

test.rb:17:in:“45”的未定义方法“-”:字符串 (命名者)

有人能告诉我我缺少什么吗?我试着用谷歌搜索,但没用,可能只是因为我不确定自己在找什么。代码如下,提前感谢

puts "This program will convert temperatures from Celcius to Fahrenheit" 
puts "or Fahrenheit to Celcius"
puts "to begin, please select which unit you are converting from"
puts "enter 0 for Fahrenheit or 1 for Celcius"
unit_from=gets.chomp
puts "please input the temperature"
degrees_from=gets.chomp

#this is the formula for celcius to fahrenheit
Celcius=(degrees_from-32)*(5/9)

#this is the formula for fahrenheit to celcius
Fahrenheit=(degrees_from)*(1.8)+32

if unit_from = 0
    puts Celcius
elsif unit_from =  1
    puts Fahrenheit
else 
    puts "You have entered and invalid option."
end

测试相等性需要两个相等项,如下所示

if unit_from == 0
    puts Celcius
elsif unit_from ==  1
    puts Fahrenheit
else 
    puts "You have entered and invalid option."
end
返回一个字符串:

获取(sep=$/)→ 字符串或零
获取(限制)→ 字符串或零
获取(sep,限制)→ 字符串或零
ARGV
(或
$*
)中的文件列表返回下一行(并将其分配给
$);如果命令行上没有文件,则从标准输入返回下一行

然后调用该字符串并获得另一个字符串:

chomp(分隔符=$/)→ 新的_str
返回一个新的
字符串
,其中给定的记录分隔符已从str结尾移除(如果存在)

这意味着您有来自
unit\u和来自
degrees\u中的字符串:

unit_from    = gets.chomp
#...
degrees_from = gets.chomp
字符串对减法一无所知,因此
度数\u from-32
会给您一个错误。如果您想使用整数输入,则需要进行几个调用:

下一个问题是
5/9
是整数除法,因此
5/9
只是一种复杂的写入
0
的方法。您需要浮点,因此应该使用
5.0/9
5/9.0
5

之后的下一个问题是,如果

if unit_from = 0
  puts Celcius
elsif unit_from =  1
  puts Fahrenheit
else 
  puts "You have entered and invalid option."
end
总是会说
放塞尔修斯
unit_from=0
是赋值,不是比较;Ruby中的赋值也是一个表达式,因此
如果unit_from=0
在语法上有效,但在逻辑上无效;赋值的值是它的右边,因此
unit\u from=0
(作为一个表达式)就是
0
,因为
0
在Ruby中是真实的,所以您总是会在第一个分支中结束。您想使用
==
进行比较:

if unit_from == 0
  puts Celcius
elsif unit_from ==  1
  puts Fahrenheit
else 
  puts "You have entered and invalid option."
end

unit_from和degrees_from的值都是字符串,很明显,不能对字符串进行乘法。首先把它们转换成整数

unit_from=gets.chomp.to_i
puts "please input the temperature"
degrees_from=gets.chomp.to_i
to_i用于将任何字符串转换为整数。例如: “2”是一个字符串,用于将其转换为整数

2.0.0-p247 :001 > "2"
 => "2" 
2.0.0-p247 :002 > "2".class
 => String 
2.0.0-p247 :003 > "2".to_i
 => 2 
2.0.0-p247 :004 > "2".to_i.class
 => Fixnum 
另外,“=”是赋值运算符,即 a=2,仅将值2赋给变量a

要检查a的值是否为2,我们需要使用“==”


太棒了,非常感谢你们的帮助。它开始走到一起了!非常感谢!我试过了,但上面说我必须有15个声誉,我不犯罪,我刚开始我的个人资料。啊哈,我明白你在说什么了。完成。再次感谢你的帮助!我一直在努力,但没有成功。我又试了一次,但如果他不接受,我就无能为力了。我在手机上,所以这可能与我有关。
2.0.0-p247 :001 > "2"
 => "2" 
2.0.0-p247 :002 > "2".class
 => String 
2.0.0-p247 :003 > "2".to_i
 => 2 
2.0.0-p247 :004 > "2".to_i.class
 => Fixnum 
2.0.0-p247 :006 > a = 2
 => 2 
2.0.0-p247 :007 > puts a
2
 => nil 
2.0.0-p247 :008 > a == 2
 => true