diff --git a/README.md b/README.md index 58c8cd5..28cf63b 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ smart people at [Hashrocket](http://hashrocket.com/). ### ruby - [Are They All True?](ruby/are-they-all-true.md) +- [Assoc For Hashes](ruby/assoc-for-hashes.md) - [Comparing Class Hierarchy Relationships](ruby/comparing-class-hierarchy-relationships.md) - [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md) - [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) diff --git a/ruby/assoc-for-hashes.md b/ruby/assoc-for-hashes.md new file mode 100644 index 0000000..1847dd8 --- /dev/null +++ b/ruby/assoc-for-hashes.md @@ -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 +```