Skip to content

Latest commit

 

History

History
19 lines (15 loc) · 417 Bytes

assoc-for-hashes.md

File metadata and controls

19 lines (15 loc) · 417 Bytes

Assoc For Hashes

Ruby's Hash class comes with a method, assoc, which is good for grabbing both the key and value from a hash. If the given key matches it returns a two element array with the key and value.

> stuff = {a: 1, b: 2, c: 3}
=> {a: 1, b: 2, c: 3}
> stuff.assoc(:c)
=> [:c, 3]

If a key is used that doesn't exist in the hash, then it simply returns nil.

> {}.assoc(:c)
=> nil