Say I have a Ruby class, Flight. Flight has an attr_accessor :key on it. If there’s an array of instances of this class: flights = [flight1, flight2, flight3], I have a “target key”, say “2jf345”, and I want to find a flight based on it’s key, from that array – what sort of code should I use?
This is the code I was going to use:
flights[flights.map { |s| s.key }.index(target_key)]
But it seems like with Ruby, there should be a simpler way. Also, the code above returns an error for me – `[]': no implicit conversion from nil to integer (TypeError). I assume this means that it’s not returning an index at all.
Thanks for any help.
You can just use
findto get the Flight object, instead of trying to useindexto get the index:However your error message suggests that
index(target_key)returnsnil, which means that you don’t actually have a flight with the key you’re looking for, which means thatfindwill returnnilas well.