diff --git a/README.md b/README.md index 55195b5..9e8c3ed 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_939 TILs and counting..._ +_940 TILs and counting..._ --- @@ -790,6 +790,7 @@ _939 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) +- [Turn Key And Value Arrays Into A Hash](ruby/turn-key-and-values-arrays-into-a-hash.md) - [Turning Any Class Into An Enumerator](ruby/turning-any-class-into-an-enumerator.md) - [Turning Things Into Hashes](ruby/turning-things-into-hashes.md) - [Uncaught Exceptions In Pry](ruby/uncaught-exceptions-in-pry.md) diff --git a/ruby/turn-key-and-values-arrays-into-a-hash.md b/ruby/turn-key-and-values-arrays-into-a-hash.md new file mode 100644 index 0000000..6dad618 --- /dev/null +++ b/ruby/turn-key-and-values-arrays-into-a-hash.md @@ -0,0 +1,22 @@ +# Turn Key And Value Arrays Into A Hash + +Let's say you have an array of keys and an array of values: + +```ruby +keys = [:title, :author, :year] +values = ["The Fifth Season", "N. K. Jemisin", 2015] +``` + +You can turn them into a hash where the keys of that hash come from `keys` and +are tied in order, one-to-one with the `values`. + +A `hash` can be created from an array of tuples, where each is a key-value +pairing. Knowing this, we can `zip` the two arrays together and then turn them +into a `hash` like so: + +```ruby +> Hash[keys.zip(values)] +#=> {:title=>"The Fifth Season", :author=>"N. K. Jemisin", :year=>2015} +``` + +[source](https://stackoverflow.com/a/23113943/535590)