简体   繁体   中英

Getting a 'Type Error' When Iterating Through a Ruby Array

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

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 in animals[i] it is not an integer and cannot be converted to one.

animals.each do |animal|
    empty_array << animal if new_animal != animal
end

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:

animals.index(new_animal) 

which will return nil if it is not in the array or the fixnum position if it is in the array

Michael got it right... when you run this code

animals = ['rhino', 'giraffe', 'cat', 'dolphin', 'turtle']
animals.each {|i| puts i}

you get:

rhino
giraffe
cat
dolphin
turtle

so "i" does not refer to what you expect it to refer to...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM