From 73071f605991f4b3870845d702be536b540fcf34 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 24 Apr 2015 08:41:04 -0500 Subject: [PATCH] Add Destructuring Arrays In Blocks as a ruby til. --- README.md | 1 + ruby/destructuring-arrays-in-blocks.md | 38 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 ruby/destructuring-arrays-in-blocks.md diff --git a/README.md b/README.md index bbab1bb..76674d8 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Are They All True?](ruby/are-they-all-true.md) - [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md) +- [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) - [Limit Split](ruby/limit-split.md) - [Parallel Bundle Install](ruby/parallel-bundle-install.md) - [Summing Collections](ruby/summing-collections.md) diff --git a/ruby/destructuring-arrays-in-blocks.md b/ruby/destructuring-arrays-in-blocks.md new file mode 100644 index 0000000..9f564c1 --- /dev/null +++ b/ruby/destructuring-arrays-in-blocks.md @@ -0,0 +1,38 @@ +# Destructuring Arrays In Blocks + +If I am iterating over a collection of arrays (let's say tuples) and I want +to access the values of those arrays within the iteration block, I may do +something like the following: + +```ruby +> a = [[1,2],[3,4],[5,6]] +> a.each { |tuple| puts "#{tuple[0]} - #{tuple[1]}" } +1 - 2 +3 - 4 +5 - 6 +``` + +I can, however, use array destructuring which will not only simplify the +code, but also make it more readable, explicit, and intentional. + +```ruby +> a = [[1,2],[3,4],[5,6]] +> a.each { |x_coord,y_coord| puts "#{x_coord} - #{y_coord}" } +1 - 2 +3 - 4 +5 - 6 +``` + +In the same way, I can destructure arrays that are part of a hash like so: + +```ruby +> h = {one: [1,2], two: [3,4], three: [5,6]} +> h.each { |key, (x_coord, y_coord)| puts "#{x_coord} - #{y_coord}" } +1 - 2 +3 - 4 +5 - 6 +``` + +Note the parentheses that are placed around the part that is being +destructured. Without these parentheses, ruby will interpret `x_coord` as +the whole array value and `y_coord` will be `nil`.