Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Hash#assoc

(::Hash::_Equals key) -> [ K, V ]?
assoc(key) → entry or nil

If the given key is found, returns its entry as a 2-element array containing that key and its value:

Example
h = {foo: 0, bar: 1, baz: 2}
h.assoc(:bar) # => [:bar, 1]

Returns nil if the key is not found.

Related: see Methods for Fetching.

See also #any? #clear #[]= #compact also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0