diff --git a/README.md b/README.md index 6012b40..5de6f2c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_820 TILs and counting..._ +_821 TILs and counting..._ --- @@ -674,6 +674,7 @@ _820 TILs and counting..._ - [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md) - [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md) - [Summing Collections](ruby/summing-collections.md) +- [Turning Things Into Hashes](ruby/turning-things-into-hashes.md) - [Uncaught Exceptions In Pry](ruby/uncaught-exceptions-in-pry.md) - [`undef_method` And The Inheritance Hierarchy](ruby/undef-method-and-the-inheritance-hierarchy.md) - [Up And Down With Integers](ruby/up-and-down-with-integers.md) diff --git a/ruby/turning-things-into-hashes.md b/ruby/turning-things-into-hashes.md new file mode 100644 index 0000000..e5b706a --- /dev/null +++ b/ruby/turning-things-into-hashes.md @@ -0,0 +1,48 @@ +# Turning Things Into Hashes + +We have `#to_h` for turning things into hashes. + +It works as an identity function: + +```ruby +> {}.to_h +=> {} +> {hello: "world"}.to_h +=> {:hello=>"world"} +``` + +It works with `nil`: + +```ruby +> nil.to_h +=> {} +``` + +Does it work with arrays? + +```ruby +> [:one, 2].to_h +TypeError: wrong element type Symbol at 0 (expected array) +from (pry):36:in `to_h' +``` + +Yes, but only if it is an array of pairs: + +```ruby +> [[:one, 2], [:three, 4]].to_h +=> {:one=>2, :three=>4} +``` + +It also works with `Struct` and `OpenStruct`: + +``` +> Person = Struct.new(:name, :age) +=> Person +> bob = Person.new("bob", 45) +=> # +> bob.to_h +=> {:name=>"bob", :age=>45} +``` + +You'll find that many other objects and gems support `#to_h` when it makes +sense.