We write 2023: (so for all stumbling in here)
find
is what you are searching for.
But find
returns an array on match or NIL for no match. If we use the argument of find
(a proc that is called if no match), and use proc {[]}
, we get an empty array on a non-matching find, that fits better to a hash.
people = {
ralph: { name: "rafael", … },
eve: { name: "eveline", … }
…
}
people[:eve] => {name: "eveline",…}
people.find { |nick, person| person.name=="rafael" }[1] => { name: "rafael", … }
and
people[:tosca] => nil
people.find { |nick, person| person.name=="toska" }[1] => BANG ([] on nil)
but
people.find(proc {[]}) { |nick, person| person.name=="toska" }[1] => nil
So if you have an id-like attribute, you can do like that:
person=people[id]
person||=people.find({[]}) { |p| p.nick == id }[1]
person||=people.find({[]}) { |p| p.other_nick == id }[1]
raise error unless person
find
andselect
is thatfind
returns the first match andselect
(which is aliased byfindAll
) returns all matches. – Lindley