Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Hash#assoc
(K arg0) -> [ K, V ]?
hash.assoc(key) → new_array or nil
hash.c
View on GitHub ↗
static VALUE
rb_hash_assoc(VALUE hash, VALUE key)
{
VALUE args[2];
if (RHASH_EMPTY_P(hash)) return Qnil;
if (RHASH_ST_TABLE_P(hash) && !RHASH_IDENTHASH_P(hash)) {
VALUE value = Qundef;
st_table assoctable = *RHASH_ST_TABLE(hash);
assoctable.type = &(struct st_hash_type){
.compare = assoc_cmp,
.hash = assoctable.type->hash,
};
VALUE arg = (VALUE)&(struct assoc_arg){
.tbl = &assoctable,
.key = (st_data_t)key,
};
if (RB_OBJ_FROZEN(hash)) {
value = assoc_lookup(arg);
}
else {
hash_iter_lev_inc(hash);
value = rb_ensure(assoc_lookup, arg, hash_foreach_ensure, hash);
}
hash_verify(hash);
if (!UNDEF_P(value)) return rb_assoc_new(key, value);
}
args[0] = key;
args[1] = Qnil;
rb_hash_foreach(hash, assoc_i, (VALUE)args);
return args[1];
}
If the given key is found, returns 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 key key is not found.