File tree 2 files changed +50
-1
lines changed
2 files changed +50
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
10
10
For a steady stream of TILs from a variety of rocketeers, checkout
11
11
[ til.hashrocket.com] ( https://til.hashrocket.com/ ) .
12
12
13
- _ 820 TILs and counting..._
13
+ _ 821 TILs and counting..._
14
14
15
15
---
16
16
@@ -674,6 +674,7 @@ _820 TILs and counting..._
674
674
- [ Squeeze Out The Extra Space] ( ruby/squeeze-out-the-extra-space.md )
675
675
- [ String Interpolation With Instance Variables] ( ruby/string-interpolation-with-instance-variables.md )
676
676
- [ Summing Collections] ( ruby/summing-collections.md )
677
+ - [ Turning Things Into Hashes] ( ruby/turning-things-into-hashes.md )
677
678
- [ Uncaught Exceptions In Pry] ( ruby/uncaught-exceptions-in-pry.md )
678
679
- [ ` undef_method ` And The Inheritance Hierarchy] ( ruby/undef-method-and-the-inheritance-hierarchy.md )
679
680
- [ Up And Down With Integers] ( ruby/up-and-down-with-integers.md )
Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments