From 12388e8cc7631f9b0fd56cb79d8c06c4a9c0e0af Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 30 Jan 2021 22:04:40 -0600 Subject: [PATCH] Add Pattern Matching Values From A Hash as a ruby til --- README.md | 3 ++- ruby/pattern-match-values-from-a-hash.md | 32 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 ruby/pattern-match-values-from-a-hash.md diff --git a/README.md b/README.md index 6ae989a..555a78e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1030 TILs and counting..._ +_1031 TILs and counting..._ --- @@ -855,6 +855,7 @@ _1030 TILs and counting..._ - [Pass A Block To Count](ruby/pass-a-block-to-count.md) - [Passing Arbitrary Methods As Blocks](ruby/passing-arbitrary-methods-as-blocks.md) - [Passing Arguments To A Rake Task](ruby/passing-arguments-to-a-rake-task.md) +- [Pattern Match Values From A Hash](ruby/pattern-match-values-from-a-hash.md) - [Percent Notation](ruby/percent-notation.md) - [Question Mark Operator](ruby/question-mark-operator.md) - [Rake Only Lists Tasks With Descriptions](ruby/rake-only-lists-tasks-with-descriptions.md) diff --git a/ruby/pattern-match-values-from-a-hash.md b/ruby/pattern-match-values-from-a-hash.md new file mode 100644 index 0000000..d41a244 --- /dev/null +++ b/ruby/pattern-match-values-from-a-hash.md @@ -0,0 +1,32 @@ +# Pattern Match Values From A Hash + +As of Ruby 3.0.0, the _rightward assignment_ operator (`=>`) was introduced as +another syntax for assigning values to variables. With it comes an experimental +pattern matching capability. This pattern matching can be used with hashes to +extract keyed values into local variables. + +Pattern matching with rightward assignment can be done by placing a hash on the +left-hand side of the `=>` operator and then placing a hash-like listing of +keys to be matched against. + +```ruby +> some_hash = { name: "Josh", handle: "@jbrancha", age: :unknown } +=> {:name=>"Josh", :handle=>"@jbrancha", :age=>:unknown} +> some_hash => {name:, handle:} +(irb):3: warning: One-line pattern matching is experimental, and the behavior may change in future versions of Ruby! +=> nil +> name +=> "Josh" +> handle +=> "@jbrancha" +``` + +This example extracts `name` and `handle` as local variables assigned with the +values of the those keys from the hash. + +Note that this feature is _experimental_. + +Also note that referencing a key that doesn't exist in a pattern matching +statement will raise a `NoMatchingPatternError`. + +[source](https://www.ruby-lang.org/en/news/2020/12/25/ruby-3-0-0-released/)