Hash#rassoc
Hash#rassoc searches a hash for a given value and returns the matching key-value pair as a two-element array [key, value]. It is the reverse of Hash#assoc — where assoc searches by key, rassoc searches by value.
Basic Usage
scores = { alice: 95, bob: 87, carol: 92 }
scores.rassoc(87)
# => [:bob, 87]
scores.rassoc(100)
# => nil
When a match is found, the key and value are returned together. When no match exists, rassoc returns nil.
Signature
rassoc(value)
Returns the first key-value pair where the value matches the given argument. The search proceeds in insertion order and stops on the first match.
Searching with Different Value Types
products = {
"SKU-001" => "Widget",
"SKU-002" => "Gadget",
"SKU-003" => "Widget Pro"
}
products.rassoc("Widget")
# => ["SKU-001", "Widget"]
products.rassoc("Gadget")
# => ["SKU-002", "Gadget"]
Works with strings, numbers, symbols, arrays, or any object type that supports ==.
Comparing with Other Hash Methods
| Method | Searches by | Returns |
|---|---|---|
assoc | key | [key, value] or nil |
rassoc | value | [key, value] or nil |
key | value | key or nil |
fetch | key (with default) | value or default |
dig | nested key path | value or nil |
Use rassoc when you have a value and need the corresponding key. This comes up when building inverse mappings or looking up records by a non-key field.
Limitations
Only returns the first match. If multiple entries share the same value, only the first one in insertion order is returned:
names = { alice: "Engineer", bob: "Designer", carol: "Engineer" }
names.rassoc("Engineer")
# => [:alice, "Engineer"]
# carol is not reached
Linear search. The hash is scanned from the beginning, making this O(n) regardless of hash size. For large hashes with frequent lookups, consider maintaining a reverse index.
No block form. Unlike select or find, there is no variant that accepts a block.
See Also
- /reference/hash-methods/has-key/ — check if a key exists
- /reference/array-methods/assoc/ — search an array of arrays by first element
- /guides/ruby-hash-tricks/ — practical hash patterns including inverse lookups