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#[]

(::Hash::_Key key) -> V
self[key] → object

Searches for a hash key equivalent to the given key; see Hash Key Equivalence.

If the key is found, returns its value:

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

Otherwise, returns a default value (see Hash Default).

Related: []=; see also Methods for Fetching.

See also .[] #[]= #>= #> also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0