2013-04-30 71 views
1

在ruby中,我尝试将运算符'[]'中的字符串转换为Int,但失败。 下面是代码(我的输入为14 45):无法在`[]`中将字符串转换为int

STDIN.gets.split(/\s+/).each do |str| 
    book = tags[str.to_i]  # book is just a new variable. tags is an array 
end 

红宝石将因错误而停止: in '[]': no implicit conversion of String into Integer (TypeError)

所以我改变我的代码如下(这个效果很好。):

STDIN.gets.split(/\s+/).each do |str| 
    number = str.to_i  # for converting 
    book = tags[number] 
end 

这个效果很好。但是我必须添加一行转换。有避免这条线的好方法吗? 我的红宝石版本是:$: ruby --version ==> ruby 2.0.0p0 (2013-02-24 revision39474) [i686-linux]

嗨,请让我知道你为什么还想关闭这个话题。谢谢。

+2

什么是'tags','db'和'book'?如果你的代码不起作用,那么第二部分也不起作用。您可能正在'db [book]'处调用'array [nil]'。 – oldergod 2013-04-30 06:33:21

+0

@oldergod,嗨,我只是修改它。而且我不认为我在调用array [nil]。使用相同的输入,我的代码的第二个版本运行良好。 – madper 2013-04-30 06:55:25

+0

人们想关闭这个话题,因为缺乏信息使得观众很难理解你的问题和/或复制它。 – oldergod 2013-04-30 08:29:01

回答

6

您收到的错误消息肯定会是只有当您将String作为Array#[]的索引时,才会发生。所以你可能没有向我们展示你实际运行的源代码。试想一下:

a = [1,2,3] 
str = 'string' 

str.to_i 
#=> 0 
a[str.to_i] 
#=> 1 

number = str.to_i 
#=> 0 
a[number] 
#=> 1 

a['string'] 
# TypeError: no implicit conversion of String into Integer 

顺便说一句,在你的问题的错误消息是具体到Ruby 2.0.0:

RUBY_VERSION 
#=> "2.0.0" 

a = [1,2,3] 
a['string'] 
# TypeError: no implicit conversion of String into Integer 

而在Ruby的1.9.3-P392,您将收到此错误信息:

​​