mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Wrap Things In An Array, Even Hashes as a ruby til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||||
|
|
||||||
_825 TILs and counting..._
|
_826 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -686,6 +686,7 @@ _825 TILs and counting..._
|
|||||||
- [Use dotenv In A Non-Rails Project](ruby/use-dotenv-in-a-non-rails-project.md)
|
- [Use dotenv In A Non-Rails Project](ruby/use-dotenv-in-a-non-rails-project.md)
|
||||||
- [Using BCrypt To Create And Check Hashed Passwords](ruby/using-bcrypt-to-create-and-check-hashed-passwords.md)
|
- [Using BCrypt To Create And Check Hashed Passwords](ruby/using-bcrypt-to-create-and-check-hashed-passwords.md)
|
||||||
- [Who Are My Ancestors?](ruby/who-are-my-ancestors.md)
|
- [Who Are My Ancestors?](ruby/who-are-my-ancestors.md)
|
||||||
|
- [Wrap Things In An Array, Even Hashes](ruby/wrap-things-in-an-array-even-hashes.md)
|
||||||
- [Zero Padding](ruby/zero-padding.md)
|
- [Zero Padding](ruby/zero-padding.md)
|
||||||
|
|
||||||
### tmux
|
### tmux
|
||||||
|
|||||||
37
ruby/wrap-things-in-an-array-even-hashes.md
Normal file
37
ruby/wrap-things-in-an-array-even-hashes.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# Wrap Things In An Array, Even Hashes
|
||||||
|
|
||||||
|
I've always used `Kernel::Array` to wrap things in an array. It works great.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
> Array(nil)
|
||||||
|
#=> []
|
||||||
|
> Array(1)
|
||||||
|
#=> [1]
|
||||||
|
> Array(["hello", "world"])
|
||||||
|
#=> ["hello", "world"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Except with hashes, it might not do what you expect when given a hash.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
> Array({a: 1, b: 2})
|
||||||
|
#=> [[:a, 1], [:b, 2]]
|
||||||
|
```
|
||||||
|
|
||||||
|
I just wanted the hash wrapped in an array, not turned into an array of tuples.
|
||||||
|
|
||||||
|
The `Array` class has a method `#wrap` which behaves similarly to
|
||||||
|
`Kernal::Array` while also handling hashes in the way I was wanting.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
> Array.wrap(nil)
|
||||||
|
#=> []
|
||||||
|
> Array.wrap(1)
|
||||||
|
#=> [1]
|
||||||
|
> Array.wrap(["hello", "world"])
|
||||||
|
#=> ["hello", "world"]
|
||||||
|
> Array.wrap({a: 1, b: 2})
|
||||||
|
#=> [{a: 1, b: 2}]
|
||||||
|
```
|
||||||
|
|
||||||
|
[source](https://devdocs.io/rails~5.2/array#method-c-wrap)
|
||||||
Reference in New Issue
Block a user