无法在“中将字符串更改为int
在ruby中,我尝试在运算符’ []
‘中将String转换为Int但是失败了。 这是代码(我的输入是14 45
):
STDIN.gets.split(/\s+/).each do |str| book = tags[str.to_i] # book is just a new variable. tags is an array end
ruby将因错误而停止: 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版本是: $: ruby --version ==> ruby 2.0.0p0 (2013-02-24 revision39474) [i686-linux]
嗨大家好,请让我知道为什么你还想关闭这个话题。 谢谢。
当您将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中,您将收到以下错误消息:
RUBY_VERSION #=> "1.9.3" a = [1,2,3] a['string'] # TypeError: can't convert String into Integer