From 21cf25f8201f20a6b39e462efb6515fba560fc7a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 1 Apr 2019 13:35:18 -0500 Subject: [PATCH] Add Pipe Into A Case Statement as an elixir til --- README.md | 3 ++- elixir/pipe-into-a-case-statement.md | 33 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 elixir/pipe-into-a-case-statement.md diff --git a/README.md b/README.md index 4e39597..2667170 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/). -_800 TILs and counting..._ +_801 TILs and counting..._ --- @@ -147,6 +147,7 @@ _800 TILs and counting..._ - [Match On A Map In A With Construct](elixir/match-on-a-map-in-a-with-construct.md) - [Passing Around And Using Modules](elixir/passing-around-and-using-modules.md) - [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md) +- [Pipe Into A Case Statement](elixir/pipe-into-a-case-statement.md) - [Quitting IEx](elixir/quitting-iex.md) - [Range Into List Using Comprehensions](elixir/range-into-list-using-comprehensions.md) - [Refer To A Module Within Itself](elixir/refer-to-a-module-within-itself.md) diff --git a/elixir/pipe-into-a-case-statement.md b/elixir/pipe-into-a-case-statement.md new file mode 100644 index 0000000..b336caa --- /dev/null +++ b/elixir/pipe-into-a-case-statement.md @@ -0,0 +1,33 @@ +# Pipe Into A Case Statement + +The standard use of a case statement looks something like this: + +```elixir +case HTTPoison.get(url) do + {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> + IO.puts body + {:ok, %HTTPoison.Response{status_code: 404}} -> + IO.puts "Not found :(" + {:error, %HTTPoison.Error{reason: reason}} -> + IO.inspect reason +end +``` + +If you are a fan of the pipe syntax, then you may enjoying writing the above +like this: + +```elixir +url +|> HTTPoison.get() +|> case do + {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> + IO.puts body + {:ok, %HTTPoison.Response{status_code: 404}} -> + IO.puts "Not found :(" + {:error, %HTTPoison.Error{reason: reason}} -> + IO.inspect reason +end +``` + +Just like any function, the value from the previous line in the pipe will be +passed in and used as the value switched over in the case statement.