1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Hash Slicing as a rails til.

This commit is contained in:
jbranchaud
2015-08-13 17:11:22 -05:00
parent 3494354ad9
commit 8321952537
2 changed files with 22 additions and 0 deletions

View File

@@ -95,6 +95,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
- [Code Statistics For An Application](rails/code-statistics-for-an-application.md)
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
- [Hash Slicing](rails/hash-slicing.md)
- [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md)
- [Pretend Generations](rails/pretend-generations.md)
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)

21
rails/hash-slicing.md Normal file
View File

@@ -0,0 +1,21 @@
# Hash Slicing
Rails' ActiveSupport adds
[`#slice`](http://api.rubyonrails.org/classes/Hash.html#method-i-slice) and
[`#slice!`](http://api.rubyonrails.org/classes/Hash.html#method-i-slice-21)
to the `Hash` class. The interface of these two methods seems a little
inconsistent though.
```ruby
> {a: 1, b: 2, c: 3}.slice(:a)
=> {:a=>1}
```
The `#slice` method returns what is being sliced.
```ruby
> {a: 1, b: 2, c: 3}.slice!(:a)
=> {:b=>2, :c=>3}
```
The `#slice!` method, on the other hand, returns what is being excluded.