收到“类型错误”迭代 Ruby 数组时
我收到以下错误:
无法将字符串转换为整数(类型错误)
它发生在这一行:
if new_animal != animals[i]
为什么会发生这种情况?
animals = ['rhino', 'giraffe', 'cat', 'dolphin', 'turtle']
puts 'Enter the new animal:'
new_animal = gets.chomp
empty_array = []
animals.each do |i|
if new_animal != animals[i]
empty_array << i
end
end
I am getting the following error:
Can't convert String into Integer (TypeError)
It is happening on this line:
if new_animal != animals[i]
Why is this happening?
animals = ['rhino', 'giraffe', 'cat', 'dolphin', 'turtle']
puts 'Enter the new animal:'
new_animal = gets.chomp
empty_array = []
animals.each do |i|
if new_animal != animals[i]
empty_array << i
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
animals.each do |i|
并没有按照你想象的那样做。i
是实际的字符串(动物名称)。因此,如果您在animals[i]
中迭代并使用动物名称作为数组访问器,它就不是整数,无法转换为整数。是正确的方法。
在 Ruby 中,如果你想要一个迭代器整数,你可以执行each_index,这将为你提供整数位置。不过,
each_index
在 Ruby 中使用得并不多,这就是为什么我将您的代码重构为我发布的内容。或者你可以只用一行代码并执行以下操作:
如果不在数组中,则返回 nil;如果在数组中,则返回 fixnum 位置
animals.each do |i|
is not doing what you think it does.i
then is the actual strings (animal names). So if you iterate through and use an animal name as an array accessor inanimals[i]
it is not an integer and cannot be converted to one.is the correct way to do it.
In Ruby if you want an iterator integer, you can do
each_index
and that will give you the integer position.each_index
is not used too much in Ruby though, that is why I refactored your code to what I posted.Or you can just make it one line of code and do:
which will return nil if it is not in the array or the fixnum position if it is in the array
迈克尔说得对...当您运行此代码时,
您会得到:
所以“i”并不指代您期望它指代的内容...
Michael got it right... when you run this code
you get:
so "i" does not refer to what you expect it to refer to...