user785100
user785100

Reputation:

Ruby array methods for locating based on an object's attribute?

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.

Upvotes: 16

Views: 16321

Answers (1)

sepp2k
sepp2k

Reputation: 370132

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.

Upvotes: 30

Related Questions