通过Ruby数组迭代时获取'类型错误'

Mel*_*bel 0 ruby arrays iteration

我收到以下错误:

无法将String转换为Integer(TypeError)

它发生在这条线上:

if new_animal != animals[i]
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

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
Run Code Online (Sandbox Code Playgroud)

Mic*_*ile 5

animals.each do |i|没有做你认为它做的事情. i然后是实际的字符串(动物名称).因此,如果您遍历并使用动物名称作为数组访问器,animals[i]则它不是整数,也不能转换为一个整数.

animals.each do |animal|
    empty_array << animal if new_animal != animal
end
Run Code Online (Sandbox Code Playgroud)

是正确的方法.

在Ruby中如果你想要一个迭代器整数,你可以这样做each_index,这将给你整数位置. each_index但是在Ruby中没有使用太多,这就是为什么我将你的代码重构为我发布的内容.

或者你可以只做一行代码并做:

animals.index(new_animal) 
Run Code Online (Sandbox Code Playgroud)

如果它不在数组中,则返回nil;如果在数组中,则返回fixnum位置