mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Assoc For Hashes as a ruby til.
This commit is contained in:
19
ruby/assoc-for-hashes.md
Normal file
19
ruby/assoc-for-hashes.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# 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.
|
||||
|
||||
```ruby
|
||||
> 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.
|
||||
|
||||
```ruby
|
||||
> {}.assoc(:c)
|
||||
=> nil
|
||||
```
|
||||
Reference in New Issue
Block a user