Skip to content

Commit 7283ada

Browse files
committed
Add Turning Things Into Hashes as a ruby til
1 parent 4953510 commit 7283ada

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_820 TILs and counting..._
13+
_821 TILs and counting..._
1414

1515
---
1616

@@ -674,6 +674,7 @@ _820 TILs and counting..._
674674
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
675675
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
676676
- [Summing Collections](ruby/summing-collections.md)
677+
- [Turning Things Into Hashes](ruby/turning-things-into-hashes.md)
677678
- [Uncaught Exceptions In Pry](ruby/uncaught-exceptions-in-pry.md)
678679
- [`undef_method` And The Inheritance Hierarchy](ruby/undef-method-and-the-inheritance-hierarchy.md)
679680
- [Up And Down With Integers](ruby/up-and-down-with-integers.md)

ruby/turning-things-into-hashes.md

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Turning Things Into Hashes
2+
3+
We have `#to_h` for turning things into hashes.
4+
5+
It works as an identity function:
6+
7+
```ruby
8+
> {}.to_h
9+
=> {}
10+
> {hello: "world"}.to_h
11+
=> {:hello=>"world"}
12+
```
13+
14+
It works with `nil`:
15+
16+
```ruby
17+
> nil.to_h
18+
=> {}
19+
```
20+
21+
Does it work with arrays?
22+
23+
```ruby
24+
> [:one, 2].to_h
25+
TypeError: wrong element type Symbol at 0 (expected array)
26+
from (pry):36:in `to_h'
27+
```
28+
29+
Yes, but only if it is an array of pairs:
30+
31+
```ruby
32+
> [[:one, 2], [:three, 4]].to_h
33+
=> {:one=>2, :three=>4}
34+
```
35+
36+
It also works with `Struct` and `OpenStruct`:
37+
38+
```
39+
> Person = Struct.new(:name, :age)
40+
=> Person
41+
> bob = Person.new("bob", 45)
42+
=> #<struct Person name="bob", age=45>
43+
> bob.to_h
44+
=> {:name=>"bob", :age=>45}
45+
```
46+
47+
You'll find that many other objects and gems support `#to_h` when it makes
48+
sense.

0 commit comments

Comments
 (0)