无法在`[]`中将字符串更改为int [英] Can't change Strings into int in `[]`
问题描述
在 ruby 中,我尝试在运算符 '[]
' 中将 String 转换为 Int,但失败了.这是代码(我的输入是 14 45
):
In ruby, I try to convert a String to Int in operator '[]
' But failed.
Here is the code (my input is 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 将因错误而停止:在'[]'中:没有将字符串隐式转换为整数(TypeError)
the ruby will stop with an error:
in '[]': no implicit conversion of String into Integer (TypeError)
所以我将我的代码更改为如下(这个效果很好.):
So I change my code to follows(this one works well.):
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 修订版39474) [i686-linux]
This one works well. But I must add one more line for converting. Is there a good way for avoiding that line?
my version of ruby is: $: ruby --version ==> ruby 2.0.0p0 (2013-02-24 revision39474) [i686-linux]
大家好,请让我知道您为什么仍要关闭此主题.谢谢.
Hi Guys, Please let me KNOW why you still want to close this topic. THANKS.
推荐答案
当您将 String
作为索引传递时,您收到的错误消息肯定会永远发生到 Array#[]
.因此,您可能没有向我们展示您实际运行的源代码.考虑:
The error message you are getting will definitely only ever occur when you pass a String
as an index to Array#[]
. So you are probably not showing us the source that you are actually running. Consider:
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:
By the way, the error message in your question is specific to 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 中,您将收到此错误消息:
Whereas in Ruby 1.9.3-p392 you will get this error message:
RUBY_VERSION
#=> "1.9.3"
a = [1,2,3]
a['string']
# TypeError: can't convert String into Integer
这篇关于无法在`[]`中将字符串更改为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!