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}

Comments are closed

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

3 Comments

  1. Caleb Josue Ruiz Torres on August 23, 2023 at 2:46 pm

    Wow!
    Cool.
    Thanks for putting this together fella.

    I was looking for a way to give exercises to people (Since I intent to launch my own digital school in the near future) without having to come up with an auto grader (Or even using an existing one). And this show/hide solution seems like a good alternative.

    Now, in relation to the content, thanks again.

    P.S. I was thinking you were using the Phoenix Framework for this website.

    • Mark Ericksen on August 23, 2023 at 3:35 pm

      Thanks! This is implemented in WordPress. Good luck with your digital school!

      • Caleb Josue Ruiz Torres on August 24, 2023 at 4:25 pm

        Thanks buddy!

        While some people argue to the point of exhaustion which or what tech stack is the best, you get things done. Amazing. And inspiring.

        Cool, thanks for wishing me good luck.

        Bye


        Caleb

Comments are closed on this static version of the site.