16

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.

1
  • 1
    I answered a very similar question a few days ago. Commented Nov 5, 2011 at 0:49

1 Answer 1

30

You can just use find to get the Flight object, instead of trying to use index to get the index:

flights.find {|s| s.key == target_key }

However your error message suggests that index(target_key) returns nil, which means that you don't actually have a flight with the key you're looking for, which means that find will return nil as well.

Sign up to request clarification or add additional context in comments.

3 Comments

Stupid question, but is there a reason the method isn't shown in the docs?
@Walter: It's in the docs for Enumerable, not Array, because that's where it's inherited from (same for map, select, inject and most other important higher-order methods).
Thanks for the help, feeling a bit slow today haha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.