Practice Matching a Map
You learn by doing. Here are a few exercises to play with in IEx. The solutions are here but hidden. Find the solution yourself first. Experiment. Have fun!
Exercise #1
Write the left hand side of this statement. Your goal is to only match when the map has an atom key of :amount and then binds the value for that key to the variable named value. What does the left side look like?
_your_statement = %{name: "Your Customer, Inc", amount: 142}
Exercise #2
Write the left hand side of this statement. Your goal is to only match when the map has a string key of "name" and then binds the value for that key to the variable named name. What does the left side look like?
_your_statement = %{"name" => "Your Customer, Inc", "amount" => 142}
Exercise #3
Write the left hand side of this statement. Your goal is to only match when the map has both string keys of "name" and "amount". We don’t care about the "name" value, but the key should be present. We do want the “amount” value. Bind that to a variable named amount. What does the left side look like?
_your_statement = %{"name" => "Your Customer, Inc", "amount" => 142}
3 Comments
Comments are closed on this static version of the site.

Comments are closed
This is a static version of the site. Comments are not available.