{"id":13393061,"url":"https://github.com/blackode/elixir-tips","last_synced_at":"2025-05-16T11:03:35.723Z","repository":{"id":19820732,"uuid":"88006197","full_name":"blackode/elixir-tips","owner":"blackode","description":"The Killer Elixir Tips and Tricks...from the experience...","archived":false,"fork":false,"pushed_at":"2023-02-24T11:30:20.000Z","size":9690,"stargazers_count":1081,"open_issues_count":0,"forks_count":67,"subscribers_count":60,"default_branch":"master","last_synced_at":"2025-04-09T05:04:47.271Z","etag":null,"topics":["awesome-elixir-tips","coding-tips","elixir","elixir-advanced-tips","elixir-beginner-tips","elixir-examples","elixir-expert-tips","elixir-hacks","elixir-in-pocket","elixir-pocket-tips","elixir-tips","elixir-tricks","elixirhacks","functional-programming-tips","hacks","programming-tips","snippet","snippets","tips","tricks"],"latest_commit_sha":null,"homepage":"https://elixir-tips.blackode.in/","language":"CSS","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/blackode.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-04-12T03:33:25.000Z","updated_at":"2025-03-23T01:18:14.000Z","dependencies_parsed_at":"2024-01-13T22:33:37.903Z","dependency_job_id":null,"html_url":"https://github.com/blackode/elixir-tips","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blackode%2Felixir-tips","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blackode%2Felixir-tips/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blackode%2Felixir-tips/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blackode%2Felixir-tips/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/blackode","download_url":"https://codeload.github.com/blackode/elixir-tips/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254518383,"owners_count":22084374,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["awesome-elixir-tips","coding-tips","elixir","elixir-advanced-tips","elixir-beginner-tips","elixir-examples","elixir-expert-tips","elixir-hacks","elixir-in-pocket","elixir-pocket-tips","elixir-tips","elixir-tricks","elixirhacks","functional-programming-tips","hacks","programming-tips","snippet","snippets","tips","tricks"],"created_at":"2024-07-30T17:00:41.938Z","updated_at":"2025-05-16T11:03:35.670Z","avatar_url":"https://github.com/blackode.png","language":"CSS","readme":"\n\u003clink rel=\"stylesheet\" href=\"assets/css/antimony.css\" /\u003e\n\n# Killer Elixir-Tips\n[![All Contributors](https://img.shields.io/badge/all_contributors-10-orange.svg?style=flat-square)](#contributors)\n\nElixir Tips and Tricks from the Experience of Development. \nEach part consists of 10 Unique Tips and Tricks with a clear explanation with live examples and outputs. These tips will speed up your development and save you time in typing code as well.\n\nYou can read specific parts with following links...\n\n\u003cdiv class=\"elixir-tips-parts\"\u003e\n  \u003cdiv class=\"elixir-tips-section\"\u003e\n    \u003ca href=\"part1.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips1.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n    \u003ca href=\"part2.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips2.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n  \u003c/div\u003e\n\n  \u003cdiv class=\"elixir-tips-section\"\u003e\n    \u003ca href=\"part3.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips3.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n    \u003ca href=\"part4.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips4.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n  \u003c/div\u003e\n\n  \u003cdiv class=\"elixir-tips-section\"\u003e\n   \u003ca href=\"part5.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips5.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n    \u003ca href=\"part6.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips6.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n  \u003c/div\u003e\n\n  \u003cdiv class=\"elixir-tips-section\"\u003e\n    \u003ca href=\"part7.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips7.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n    \u003ca href=\"part8.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips8.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n\u003c/div\u003e\n\n  \u003cdiv class=\"elixir-tips-section\"\u003e\n    \u003ca href=\"part9.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips9.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n    \u003ca href=\"part10.md\"\u003e\n    \u003cimg class=\"elixirtip-img\" src=\"assets/images/parts/tips10.jpg\" width=\"400px\"/\u003e\n    \u003c/a\u003e\n\u003c/div\u003e\n\n \u003c/div\u003e\n\n All Photos by [Form](https://unsplash.com/@theformfitness) on [Unsplash](https://unsplash.com)\n \n Checkout some cherry picked tips from the all Parts\n\n# Taste Before you Eat :)\n\n### iex Custom Configuration - iex Decoration\n\nCopy the content into a file and save the file as `.iex.exs` in your `~` home directory and see the magic. You can also download the file [HERE](https://gist.github.com/blackode/5728517116d7a4d08f0a4faddd8c145a)\n\n```elixir\n# IEx.configure colors: [enabled: true]\n# IEx.configure colors: [ eval_result: [ :cyan, :bright ] ]\nIO.puts IO.ANSI.red_background() \u003c\u003e IO.ANSI.white() \u003c\u003e \" ❄❄❄ Good Luck with Elixir ❄❄❄ \" \u003c\u003e IO.ANSI.reset\nApplication.put_env(:elixir, :ansi_enabled, true)\nIEx.configure(\n colors: [\n   eval_result: [:green, :bright] ,\n   eval_error: [[:red,:bright,\"Bug Bug ..!!\"]],\n   eval_info: [:yellow, :bright ],\n ],\n default_prompt: [\n   \"\\e[G\",    # ANSI CHA, move cursor to column 1\n    :white,\n    \"I\",\n    :red,\n    \"❤\" ,       # plain string\n    :green,\n    \"%prefix\",:white,\"|\",\n     :blue,\n     \"%counter\",\n     :white,\n     \"|\",\n    :red,\n    \"▶\" ,         # plain string\n    :white,\n    \"▶▶\"  ,       # plain string\n      # ❤ ❤-»\" ,  # plain string\n    :reset\n  ] |\u003e IO.ANSI.format |\u003e IO.chardata_to_string\n\n)\n```\n\n![img](https://cdn-images-1.medium.com/max/800/1*iy-IELdB8fjTo5H0sABlBQ.png)\n\n\u003chr\u003e\n\n### Creating Custom Sigils and Documenting\n\nEach `x` sigil calls its respective `sigil_x` definition\n\nDefining Custom Sigils\n\n```elixir\ndefmodule MySigils do\n  #returns the downcasing string if option l is given then returns the list of downcase letters\n  def sigil_l(string,[]), do: String.downcase(string)\n  def sigil_l(string,[?l]), do: String.downcase(string) |\u003e String.graphemes\n\n  #returns the upcasing string if option l is given then returns the list of downcase letters\n  def sigil_u(string,[]), do: String.upcase(string)\n  def sigil_u(string,[?l]), do: String.upcase(string) |\u003e String.graphemes\nend\n```\n\n#### usage\n\nLoad the module into iex\n\n```elixir\niex\u003e import MySigils\niex\u003e ~l/HELLO/\n\"hello\"\niex\u003e ~l/HELLO/l\n[\"h\", \"e\", \"l\", \"l\", \"o\"]\niex\u003e ~u/hello/\n\"HELLO\"\niex\u003e ~u/hello/l\n[\"H\", \"E\", \"L\", \"L\", \"O\"]\n```\n\n\u003chr\u003e\n\n### Custom Error Definitions\n\n#### Define Custom Error\n\n```elixir\ndefmodule BugError do\n   defexception message: \"BUG BUG ..\" # message is the default\nend\n```\n\n**Usage**\n\n```elixir\niex bug_error.ex\n\niex\u003e raise BugError\n** (BugError) BUG BUG ..\niex\u003e raise BugError, message: \"I am Bug..\" #here passing the message dynamic\n** (BugError) I am Bug..\n```\n\u003chr\u003e\n\n### Writing Protocols\n\n#### Define a Protocol\n\nA **Protocol** is a way to dispatch to a particular implementation of a function based on the type of the parameter. The macros `defprotocol` and `defimpl` are used to define Protocols and Protocol implementations respectively for different types in the following example.\n\n```elixir\ndefprotocol Triple do    \n  def triple(input)  \nend  \n\ndefimpl Triple, for: Integer do    \n  def triple(int) do     \n    int * 3   \n  end  \nend   \n\ndefimpl Triple, for: List do\n  def triple(list) do\n    list ++ list ++ list   \n  end  \nend\n```\n\n#### Usage\n\nLoad the code into `iex` and execute\n\n```elixir\niex\u003e Triple.triple(3) \n9\nTriple.triple([1, 2])\n[1, 2, 1, 2, 1, 2]\n```\n\u003chr\u003e\n\n### Ternary Operator\n\nThere is no ternary operator like `true ? \"yes\" : \"no\"` . So, the following is suggested.\n\n```elixir\n\"no\" = if 1 == 0, do: \"yes\", else: \"no\"\n```\n\u003chr\u003e\n\n### Advantage of Kernel.\\|\\|\n\nWhen using pipelines, sometimes we break the pipeline for `or` operation. For example:\n\n```elixir\nresult = :input\n|\u003e do_something\n|\u003e do_another_thing\n```\n\n```text\n# Bad\nresult = (result || :default_output)\n|\u003e do_something_else\n```\n\nIndeed, `||` is only a shortcut for `Kernel.||` . We can use `Kernel.||` in the pipeline instead to avoid breaking the pipeline.\n\nThe code above will be:\n\n```elixir\nresult = :input\n|\u003e do_something\n|\u003e do_another_thing\n|\u003e Kernel.||(:default_output)  #\u003c-- This line\n|\u003e do_something_else\n```\n\nThis above tip is from [qhwa](https://medium.com/@qhwa_85848)\n\n\u003chr\u003e\n\n### Checking Out Code Grouping\n\nCode grouping stands for something great. It shows you how your code is grouped when you write multiple lines of code in single line with out using braces. It will be more clear with the following example.\n\n```elixir\none 1 |\u003e two()\n```\n\nIf you want to see how this line of code is grouped into, you can check in the following format..\n\n```elixir\nquote(do: one 1 |\u003e two()) |\u003e Macro.to_string |\u003e IO.puts\none(1 |\u003e two())\n```\n\nSo, by using the `quote` and `Macro.to_string` you can see how our code was grouped into.\n\nThis tip came out in discussion with the creator of **Ecto** [**MichalMuskala**](https://elixirforum.com/users/michalmuskala) in the Elixir forum.\n\n\u003chr\u003e\n\n### Elixir Short Circuit Operators \u0026\u0026 — \\|\\|\n\nThese replaces the nested complicated conditions. These are my best friends in the situations dealing with more complex comparisons. Trust me you gonna love this.\n\nThe `||` operator always returns the first expression which is true. Elixir doesn’t care about the remaining expressions, and won’t evaluate them after a match has been found.\n\n#### \\|\\|\n\n```elixir\nfalse || nil || :blackode || :elixir || :jose\n```\n\nHere if you observe the first expression is false next `nil` is also false in elixir next `:blackode` which evaluates to true and its value is returned immediately with out evaluating the `:elixir` and `:jose` . Similarly if all the statements evaluates to `false` the last expression is returned.\n\n#### \u0026\u0026\n\n```elixir\niex\u003e true \u0026\u0026 :true \u0026\u0026 :elixir \u0026\u0026 5\n5\niex\u003e nil \u0026\u0026 100\nnil\niex\u003e salary = is_login \u0026\u0026 is_admin \u0026\u0026 is_staff \u0026\u0026 100_000\n```\n\nThis `\u0026\u0026` returns the second expression if the first expression is `true` or else it returns the first expression with out evaluating the second expression. In the above examples the last one is the situation where we encounter to use the `\u0026\u0026` operator.\n\n\u003chr\u003e\n\n### Comparing two different data types\n\nI have self experience with this. When I was a novice in elixir, I just compared `\"5\" \u003e 4` unknowingly by an accident and to my surprise it returned with `true`.\n\nIn **Elixir** every term can compare with every other term. So one has to be careful in comparisons.\n\n![img](https://cdn-images-1.medium.com/max/800/0*SOFSiJHylCKMOb-9.)\n\n```elixir\niex\u003e x = \"I am x \"\n\"I am x \"\niex\u003e x \u003e 34\ntrue\niex\u003e x \u003e [1,2,3]\ntrue\niex\u003e [1, 2, 3] \u003c 1234567890\nfalse\n```\n\n**Order of Comparison**\n\n\u003e number \u0026lt; atom \u0026lt; reference \u0026lt; fun \u0026lt; port \u0026lt; pid \u0026lt; tuple \u0026lt; map \u0026lt; list \u0026lt; bitstring \\(binary\\)\n\n\u003chr\u003e\n\n### Arithmetic Operators as Lambda functions\n\nWhen I see this first time, I said to my self “**Elixir is Crazy**”. This tip really saves time and it resembles your smartness. In Elixir every operator is a macro. So, we can use them as lambda functions.\n\n```elixir\niex\u003e Enum.reduce([1,2,3], 0, \u0026+/2)\n6\niex\u003e Enum.reduce([1,2,3], 0, \u0026*/2)\n0\niex\u003e Enum.reduce([1,2,3], 3, \u0026*/2)\n18\niex\u003e Enum.reduce([1,2,3], 3, \u0026-/2)\n-1\niex\u003e Enum.reduce([1,2,3], 3, \u0026//2)\n0.5\n```\n\u003chr\u003e\n\n### Binary Pattern Matching\n\nThis is my recent discovery. I always encounter a situation like converting `\"$34.56\"` which is a string and I suppose do arithmetic operations. I usually do something like this before binary pattern matching..\n\n![img](https://cdn-images-1.medium.com/max/800/0*ipJJTjsFiaGmCBpc.)\n\n```elixir\niex\u003e value = \"$34.56\"\niex ...      |\u003e String.split(\"$\")\niex ...      |\u003e tl\niex ...      |\u003e List.first\niex ...      |\u003e String.to_float\n34.56\n```\n\n#### Tip Approach\n\nThis tip makes my day easy. I recently used this is in one of my projects.\n\n```elixir\niex\u003e \"$\" \u003c\u003e value = \"$34.56\"\n\"$34.56\"\niex\u003e String.to_float value  \n34.56\n```\n\u003chr\u003e\n\n### Must Know the Differences of Map keys as :atoms and binary\\(strings\\)\n\nBefore I let you to use this tip, I just want to remind you that **:atoms** are not garbage collected. Atom keys are great! If you have a defined atoms, you are in no danger. What you should not do is converting user supplied input into atoms without sanitizing them first because it can lead to out of memory. **You should also be cautious if you create dynamic atoms in your code.**\n\nBut, you can use the `.` to retrieve the data from the keys as `map.key` unlike the usual notation like `map[\"key\"]` . That really saves on typing. But, I don’t encourage this because, as programmers we should really care about memory.\n\n![img](https://cdn-images-1.medium.com/max/800/0*DQf-KHbpd6qcgEpz.)\n\n```elixir\niex\u003e map = %{name: \"blackode\", blog: \"medium\"}\n%{blog: \"medium\", name: \"blackode\"}\n\niex\u003e map.name\n\"blackode\"\n\niex\u003e map.blog\n\"medium\"\n```\n\nBe sure that when you try to retrieve a key with `.` form which is not present in the map, it will raise a **key error** instead of returning the `nil` unlike the `map[\"key\"]` which returns `nil` if `key` is not present in a `map`.\n\n```elixir\niex\u003e map[\"age\"]\nnil\n```\n\n```text\niex\u003e map.age\nBug Bug ..!!** (KeyError) key :age not found in: %{blog: \"medium\", name: \"blackode\"}\nBug Bug ..!!\n```\n\n\u003chr\u003e\n\n### Add Some Color To Your Console Prints\n\nElixir `\u003e=1.4.0` has **ANSI** color printing option to console. You can have great fun with colors. You can also provide **background colors**.\n\n```elixir\niex\u003e import IO.ANSI\niex\u003e IO.puts red \u003c\u003e \"red\" \u003c\u003e green \u003c\u003e \" green\" \u003c\u003e yellow \u003c\u003e \" yellow\" \u003c\u003e reset \u003c\u003e \" normal\"\niex\u003e IO.puts Enum.join [red, \"red\", green, \" green\", yellow, \" yellow\", reset, \" normal\"]\nred green yellow normal\n```\n\nThe red prints in red color, green in green color, yellow in yellow color and normal in white. Have fun with colors…\n\nFor more details on color printing check [**Printex**](https://github.com/blackode/printex) module which I created for fun in Elixir.\n\n![img](https://cdn-images-1.medium.com/max/800/0*DQf-KHbpd6qcgEpz.)\n\n![img](https://cdn-images-1.medium.com/max/1000/0*Qskz94BcqMSyPAuH.png)\n\n\u003chr\u003e\n\n### Functional Macros as Guard Clauses\n\nWe cannot make use of the functions as guard clauses in elixir. It means, `when` cannot accept custom defined functions. Consider the following lines of code…\n\n```elixir\ndefmodule Hello do\n  def hello(name, age) when is_kid(age) do\n    IO.puts \"Hello Kid #{name}\"\n  end\n  \n  def hello(name, age) when is_adult(age) do\n    IO.puts \"Hello Mister #{name}\"\n  end\n  \n  def is_kid age do\n    age \u003c 12\n  end\n  \n  def is_adult age do\n    age \u003e 18\n  end\nend\n```\n\nHere we defined a **module** `Hello` and a function `hello` that takes two parameters of `name` and `age`. So, based on age I am trying `IO.puts`accordingly. If you do so you will get an error saying….\n\n```text\n** (CompileError) hello.ex:2: cannot invoke local is_kid/1 inside guard\n    hello.ex:2: (module)\n```\n\nThis is because **when** cannot accept functions as guards. We need to convert them to `macros` Lets do that…\n\n```elixir\ndefmodule MyGuards do\n\n  defmacro is_kid age do\n    quote do: unquote(age) \u003c 12\n  end\n\n  defmacro is_adult age do\n    quote do: unquote(age) \u003e 18\n  end\n\nend\n# order of module matters here.....\ndefmodule Hello do\n\n  import MyGuards\n\n  def hello(name, age) when is_kid(age) do\n    IO.puts \"Hello Kid #{name}\"\n  end\n\n  def hello(name, age) when is_adult(age) do\n    IO.puts \"Hello Mister #{name}\"\n  end\n\n   def hello(name, age) do\n    IO.puts \"Hello Youth #{name}\"\n  end\n\nend\n```\n\nIn the above lines of code, we wrapped all our guards inside a module `MyGuards` and make sure the module is top of the module `Hello` so, the macros first gets compiled. Now compile and execute you will see the following output..\n\n```elixir\niex\u003e Hello.hello \"blackode\", 21\nHello Mister blackode\n:ok\niex\u003e Hello.hello \"blackode\", 11\nHello Kid blackode\n:ok\n```\n\nStarting on Elixir v1.6, you can use [defguard/1](https://hexdocs.pm/elixir/Kernel.html#defguard/1).\n\nThe `defguard` is also a macro. You can also create private guards with `defguardp`. Hope, you got the point here.  \nConsider the following example.\n\n**NOTE**: The `defguard` and `defguardp` should reside inside the module like other macros. It raises a compile time error, if some thing that don't fit in the guard clause section `when`.\n\nSuppose, you want to check the given number is either `three` or `five`, you can define the guard as following.\n\n```elixir\ndefmodule Number.Guards do\n  defguard is_three_or_five(number) when (number===3) or (number===5)\nend\n```\n\n#### Usage\n\n```elixir\nimport Number.Guards\ndefmodule Hello do\n  def check_favorite_number(num) when is_three_or_five(num) do\n    IO.puts \"The given #{num} is on of my favourite numbers\"\n  end\n  def check_favorite_number(_num), do: IO.puts \"Not my favorite number\"\nend\n```\n\nYou can also use them inside your code logic as they results `boolean` value.\n\n```elixir\niex\u003e import Number.Guards\nNumber.Guards\n\niex\u003e is_three_or_five(5)\ntrue\n\niex\u003e is_three_or_five(3)\ntrue\n\niex\u003e is_three_or_five(1)\nfalse\n```\n\nCheck the following execution screen shot.\n\n![ScreenShot Defguard Execution](.gitbook/assets/defguard%20%281%29.png)\n\n\u003chr\u003e\n\n### Finding whether Module was loaded or not\n\nSometimes, we have to make sure that certain module is loaded before making a call to the function. We are supposed to ensure the module is loaded.\n\n```text\nCode.ensure_loaded? \u003cModule\u003e\n```\n\n```elixir\niex\u003e Code.ensure_loaded? :kernel\ntrue\niex\u003e Code.ensure_loaded :kernel\n{:module, :kernel}\n```\n\nSimilarly we are having `ensure_compile` to check whether the module is compiled or not…\n\n\u003chr\u003e\n\n### Converting Binary to Capital Atom\n\nElixir provides a special syntax which is usually used for module names. What is called a module name is an _**uppercase ASCII letter**_ followed by any number of _lowercase_ or _uppercase ASCII letters_, _numbers_, or _underscores_.\n\nThis identifier is equivalent to an atom prefixed by `Elixir.` So in the `defmodule Blackode` example `Blackode` is equivalent to `:\"Elixir.Blackode\"`\n\nWhen we use `String.to_atom \"Blackode\"` it converts it into `:Blackode` But actually we need something like “**Blackode” to Blackode**. To do that we need to use `Module.concat`\n\n```elixir\niex(2)\u003e String.to_atom \"Blackode\"\n:Blackode\niex(3)\u003e Module.concat Elixir,\"Blackode\"\nBlackode\n```\n\nIn Command line applications whatever you pass they convert it into **binary**. So, again you suppose to do some casting operations …\n\n\u003chr\u003e\n\n### Pattern match \\[ vs \\] destructure.\n\nWe all know that `=` does the pattern match for left and right side. We cannot do `[a, b, c] = [1, 2, 3, 4]` this raise a `MatchError`\n\n```elixir\niex(11)\u003e [a, b, c] = [1, 2, 3, 4]\n** (MatchError) no match of right hand side value: [1, 2, 3, 4]\n```\n\nWe can use `destructure/2` to do the job.\n\n```elixir\niex(1)\u003e destructure [a, b, c], [1, 2, 3, 4]\n[1, 2, 3]\niex(2)\u003e {a, b, c}\n{1, 2, 3}\n```\n\nIf the left side is having more entries than in right side, it assigns the `nil` value for remaining entries..\n\n```elixir\niex\u003e destructure([a, b, c], [1])\niex\u003e {a, b, c} \n{1, nil, nil}\n```\n\n\u003chr\u003e\n\n### The Goodness of Data decoration \\[ inspect with :label \\] option\n\nWe can decorate our output with `inspect` and `label` option. The string of `label` is added at the beginning of the data we are inspecting.\n\n```elixir\niex(1)\u003e IO.inspect [1, 2, 3], label: \"the list \"\nthe list : [1, 2, 3]\n[1, 2, 3]\n```\n\nIf you closely observe this it again returns the inspected data. So, we can use them as intermediate results in `|\u003e` pipe operations like following……\n\n```elixir\n[1, 2, 3] \n|\u003e IO.inspect(label: \"before change\") \n|\u003e Enum.map(\u0026(\u00261 * 2)) \n|\u003e IO.inspect(label: \"after change\") \n|\u003e length\n```\n\nYou will see the following `output`\n\n```text\nbefore change: [1, 2, 3]\nafter change: [2, 4, 6]\n3\n```\n\u003chr\u003e\n\n### Piping Anonymous functions\n\nWe can pass the anonymous functions in two ways. One is directly using `\u0026`like following..\n\n```elixir\n[1, 2, 3, 4, 5]\n|\u003e length()\n|\u003e (\u0026(\u00261*\u00261)).()\n```\n\nThis is the most weirdest approach. How ever, we can use the reference of the anonymous function by giving its name.\n\n```elixir\nsquare = \u0026 \u00261 * \u00261\n[1, 2, 3, 4, 5]\n|\u003e length()\n|\u003e square.()\n```\n\nThe above style is much better than previous . You can also use `fn` to define anonymous functions.\n\nOr use `Kernel.then/2` function since 1.12.0\n\n```elixir\n[1, 2, 3, 4, 5]\n|\u003e length()\n|\u003e then(\u0026 \u00261 * \u00261)\n```\n\n\u003chr\u003e\n\n### Retrieve Character Integer Codepoints — ?\n\nWe can use `?` operator to retrieve character integer codepoints.\n\n```elixir\niex\u003e ?a\n97\niex\u003e ?#\n35\n```\n\nThe following two tips are mostly useful for beginners…\n\n\u003chr\u003e\n\n### Performing Subtraction on Lists\n\nWe can perform the subtraction over lists for removing the elements in list.\n\n```elixir\niex\u003e [1, 2, 3, 4.5] -- [1, 2]\n[3, 4.5]\niex\u003e [1, 2, 3, 4.5, 1] -- [1]  \n[2, 3, 4.5, 1]\niex\u003e [1, 2, 3, 4.5, 1] -- [1, 1]\n[2, 3, 4.5]\niex\u003e [1, 2, 3, 4.5] -- [6]\n[1, 2, 3, 4.5]\n```\n\nWe can also perform same operations on char lists too..\n\n```elixir\niex(12)\u003e 'blackode' -- 'ode'\n'black'\niex(13)\u003e 'blackode' -- 'z'    \n'blackode'\n```\n\nIf the element to subtract is not present in the list then it simply returns the list.\n\n\u003chr\u003e\n\n### Running Multiple Mix Tasks\n\n```elixir\nmix do deps.get,compile\n```\n\nYou can run multiple tasks by separating them with coma `,`\n\nHow ever you can also create aliases in your mix project in a file called `mix.exs` .\n\nThe project definition looks like the following way when you create one using a `mix` tool.\n\n```elixir\ndef project do\n    [app: :project_name,\n     version: \"0.1.0\",\n     elixir: \"~\u003e 1.4-rc\",\n     build_embedded: Mix.env == :prod,\n     start_permanent: Mix.env == :prod,\n     deps: deps()]\n  end\n```\n\nYou are also allowed to add some extra fields…\n\nHere you have to add the `aliases` field.\n\n```elixir\n[\n aliases: aliases()\n]\n```\n\nDon’t forget to add `,` at the end when you add this in the middle of `list` .\n\nThe `aliases()` should return the `key-value` list.\n\n```elixir\ndefp aliases do\n  [\n    \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"ecto.seed\"]\n  ]\nend\n```\n\nSo, whenever you run the `mix ecto.setup` the three tasks `ecto.create`, `ecto.migrate` and `ecto.seed` will run one after the other.\n\nYou can also add them directly as following unlike I did with private function.\n\n```elixir\ndef project do\n    [app: :project_name,\n     version: \"0.1.0\",\n     aliases: [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"ecto.seed\"]]      \n.....\n  end\n```\n\n\u003chr\u003e\n\n### Accessing the Documentation\n\nElixir stores the documentation inside the `bytecode` in a memory. You access the documentation with the help of `Code.get_docs/2` function . This means, the documentation accessed when it is required, but not when it is loaded in the virtual machine like `iex`\n\nSuppose you defined a module in memory like ones you defined in **IEx**, cannot have their documentation accessed as they do not have their bytecode written to disk.\n\nLet us check this…\n\nCreate a module with name `test.ex` with the following code. You can copy and paste it.\n\n```elixir\ndefmodule Test do\n  @moduledoc \"\"\"\n  This is the test module docs\n  \"\"\"\n\n  @doc \"\"\"\n  This is the documentation of hello function\n  \"\"\"\n  def hello do\n    IO.puts \"hello\"\n  end\nend\n```\n\nNow stay in the directory where your file exists and run the command\n\n```elixir\n$ iex test.ex\n```\n\nNow you can access the function definitions but not the documentation.\n\n```elixir\niex\u003e Test.hello\nhello\n:ok\n```\n\nThat means the code is compiled but documentation is not stored in the memory. So, you cannot access the docs. Lets check that…\n\n```elixir\niex\u003e Code.get_docs Hello, :moduledoc\nnil\n```\n\nYou will see the output as `nil` when you are trying to access the **docs** of the module you have created so far. This is because, the `bytecode` is not available in disk. In simple way `beam` file is not present. Lets do that...\n\nPress `Ctrl+C` twice so you will come out of the shell and this time you run the command as\n\n```elixir\n$ elixirc test.ex\n```\n\nAfter running the command, you will see a file with name `Elixir.Test.beam` . Now the `bytecode` for the module `Test` is available in memory. Now you can access the documentation as follows...\n\n```elixir\n$ iex\niex\u003e Code.get_docs Test, :moduledoc\n{3, \"This is the test module docs\\n\"}\n```\n\nThe output is tuple with two elements. The first element is the line number of the documentation it starts and second element is the actual documentation in the binary form.\n\nYou can read more about this function [here](https://hexdocs.pm/elixir/Code.html#get_docs/2)\n\n\u003chr\u003e\n\n### Dynamic Function Name in Elixir Macro\n\nThe hack is name of a function should be an **atom** instead of binary.\n\n```elixir\ndefmacro gen_function(fun_name) do\n  quote do \n    def unquote(:\"#{fun_name}\")() do\n      # your code...\n    end\n  end\nend\n```\n\n\u003chr\u003e\n\n### Printing List as List without ASCII-Encoding\n\nYou know that when the list contains all the numbers as **ASCII** values, it will list out those values instead of the original numbers. Lets check that…\n\n```elixir\niex\u003e IO.inspect [97, 98]\n'ab'\n'ab'\n```\n\nThe code point of `a` is `97` and `b` is `98` hence it is listing out them as `char_list`. However you can tell the `IO.inspect` to list them as list itself with option `char_lists: :as_list` .\n\n```elixir\niex\u003e IO.inspect [97, 98], charlists: :as_lists\n[97, 98]\n'ab'\n```\n\nOpen `iex` and type `h Inspect.Opts`, you will see that Elixir does this kind of thing with other values as well, specifically **structs** and **binaries**.\n\n\u003chr\u003e\n\n### Fetching out file name and line number the expression is on\n\n```elixir\ndefmacro __ENV__()\n```\n\nThis macro gives the current environment information. You can get the information like current `filename` `line` `function` and others…\n\n```elixir\niex(4)\u003e __ENV__.file\n\"iex\"\n\niex(5)\u003e __ENV__.line\n5\n```\n\u003chr\u003e\n\n### Creating Manual Pids for Unit Testing\n\nYou can create the pid manually in Elixir with `pid` function. This comes with two flavors.\n\n#### def pid\\(string\\)\n\nCreates the pid from the string.\n\n```elixir\niex\u003e pid(\"0.21.32\")\n#PID\u003c0.21.32\u003e\n```\n\n#### def pid\\(a, b, c\\)\n\nCreates a **PID** with 3 non negative integers passed as arguments to the function.\n\n```elixir\niex\u003e pid(0, 21, 32)\n#PID\u003c0.21.32\u003e\n```\n\n#### Why do you create the pids manually?\n\nSuppose, you are writing a library and you want to test one of your functions for the type `pid`, then you can create one and test with it.\n\nYou cannot create the pid like assigning `pid = #PID\u003c0.21.32\u003e` because `#` is considered as comment here.\n\n```elixir\niex(6)\u003e pid = #PID\u003c0.21.32\u003e\n...(6)\u003e\n```\n\nWhen you do like above, **iex** shell just wait for more input as `#PID\u003c0.21.32\u003e` is treated as comment.\n\nNow you enter another data to complete the expression. The entered value is the value of the pid. Lets check that…\n\n```elixir\niex(6)\u003e pid = #PID\u003c0.21.32\u003e      # here expression is not complete\n...(6)\u003e 23    # here we are giving the value 23\n23            # expression is complete\niex(7)\u003e pid\n23\n```\n\u003chr\u003e\n\n### Replacing the String with global option\n\nThe `String.replace` function will replace the given the pattern with replacing pattern. By default, it replaces all the occurrences of the pattern. Lets check that…\n\n```elixir\niex(1)\u003e str = \"hello@hi.com, blackode@medium.com\"    \n\"hello@hi.com, blackode@medium.com\"\n\niex(2)\u003e String.replace str,\"@\",\"#\"\n\"hello#hi.com, blackode#medium.com\n```\n\nThe `String.replace str, \"@\", \"#\"`is same as `String.replace str, \"@\", \"#\", global: true`\n\nBut, if you want to replace only the first occurrence of the pattern, you need to pass the option `global: false` . So, it replaces only the first occurrence of `@` . Lets check that…\n\n```elixir\niex(3)\u003e String.replace str, \"@\", \"#\", global: false\n\"hello#hi.com, blackode@medium.com\"\n```\n\nHere only first `@` is replaced with `#`.\n\n\u003chr\u003e\n\n### Memory Usage\n\nYou can check the memory usage \\(in bytes\\) with `:erlang.memory`\n\n```elixir\niex(1)\u003e :erlang.memory\n[total: 16221568, processes: 4366128, processes_used: 4364992, system: 11855440,\n atom: 264529, atom_used: 250685, binary: 151192, code: 5845369, ets: 331768]\n```\n\nHowever, you can pass option like `:erlang.memory :atom` to get the memory usage of atoms.\n\n```elixir\niex(2)\u003e :erlang.memory :atom\n264529\n```\n\n\u003chr\u003e\n\n### Picking out the elements in List\n\nWe all know that a proper list is a combination of `head` and `tail` like `[head | tail]` . We can use the same principle for picking out the elements in the list like the following way…\n\n```elixir\niex\u003e [first, second, third, fourth | _rest] = [1, 2, 3, 4, 5, 6, 7]\n[1, 2, 3, 4, 5, 6, 7]\niex\u003e first\n1\niex\u003e {second, third, fourth}\n{2, 3, 4}\n```\n\n\u003chr\u003e\n\n### The combination effect of get\\_in /Access.all\\(\\)\n\nWe all know that the get\\_in function is used to extract the key which is deeper inside the map by providing the list with keys like a following way…\n\n```elixir\niex\u003e user = %{\"name\" =\u003e {\"first_name\" =\u003e \"blackode\", \"last_name\" =\u003e \"john\" }}\n%{\"name\" =\u003e %{\"first_name\" =\u003e \"blackode\", \"last_name\" =\u003e \"john\"}}\niex \u003e get_in user, [\"name\", \"first_name\"]\n\"blackode\"\n```\n\nBut, if there is a list of maps `[maps]` where you have to extract `first_name` of the each map, generally we go for `enum` . We can also achieve this by using the `get_in` and `Access.all()`\n\n```elixir\niex\u003e users=[%{\"user\" =\u003e %{\"first_name\" =\u003e \"john\", \"age\" =\u003e 23}},\n            %{\"user\" =\u003e %{\"first_name\" =\u003e \"hari\", \"age\" =\u003e 22}},\n            %{\"user\" =\u003e %{\"first_name\" =\u003e \"mahesh\", \"age\" =\u003e 21}}]\n# that is a list of maps \niex\u003e get_in users, [Access.all(), \"user\", \"age\"]\n[23, 22, 21]\n\niex\u003e get_in users, [Access.all(), \"user\", \"first_name\"]\n[\"john\", \"hari\", \"mahesh\"]\n```\n\n**Note:** If the key is not present in map, then it returns nil **Warning:** When you use the `get_in` along with `Access.all()` , as the first value in the list of keys like above, the users datatype should be list. If you pass the map, it returns the error.\n\n```elixir\niex(17)\u003e list = [%{name: \"john\"}, %{name: \"mary\"}, %{age: 34}]\n[%{name: \"john\"}, %{name: \"mary\"}, %{age: 34}]\niex(18)\u003e get_in(list, [Access.all(), :name])\n[\"john\", \"mary\", nil]\n```\n\nIn the above lines of code returns the `nil` for key which is not in the `map`.\n\n```elixir\niex(19)\u003e get_in(%{name: \"blackode\"}, [Access.all(), :name])\n** (RuntimeError) Access.all/0 expected a list, got: %{name: \"blackode\"}\n    (elixir) lib/access.ex:567: Access.all/3\n```\n\nIn the above lines of code returns the error for passing map .\n\nHowever, you can change the position of the Access.all\\(\\) in the list. But the before key should return the list. Check the following lines of code.\n\n**Deep Dive**\n\nWe can also use the Access.all\\(\\) with functions like update\\_in, get\\_and\\_update\\_in, etc..  \nFor instance, given a user with a list of books, here is how to deeply traverse the map and convert all book names to uppercase:\n\n```elixir\niex\u003e user = %{name: \"john\", books: [%{name: \"my soul\", type: \"tragedy\"}, %{name: \"my heart\", type: \"romantic\"}, %{name: \"my enemy\", type: \"horror\"}]}\niex\u003e update_in user, [:books, Access.all(), :name], \u0026String.upcase/1\n%{books: [%{name: \"MY SOUL\", type: \"tragedy\"}, %{name: \"MY HEART\", type: \"romantic\"}, %{name: \"MY ENEMY\", type: \"horror\"}], name: \"john\"}\niex\u003e get_in user, [:books, Access.all(), :name]\n[\"my soul\", \"my heart\", \"my enemy\"]\n```\n\nHere, user is not a list unlike in the previous examples where we passed the users as a list. But, we changed the position of `Access.all()` and inside the list of keys `[:books, Access.all(), :name]`, the value of the key `:books` should return the list, other wise it raises an error.\n\n\u003chr\u003e\n\n### Data Comprehension along with filters using FOR\n\nWe achieve the data comprehension through `for x \u003c- [1, 2, 3], do: x + 1` . But we can also add the comprehension along with filter.\n\n**General Usage**\n\n```elixir\niex\u003e for x \u003c- [1, 2, 3, 4], do: x + 1\n[2, 3, 4, 5]\n# that is how we use in general lets think out of the box\n```\n\n**With filters**\n\nHere I am using two lists of numbers and cross product over the lists and filtering out the product which is a odd number.\n\n```elixir\niex\u003e for x \u003c- [1, 2, 3, 4], y \u003c- [5, 6, 7, 8], rem(x * y, 2) == 0, do: {x, y, x * y}\n[{1, 5, 5}, {1, 7, 7}, {3, 5, 15}, {3, 7, 21}]\n#here rem(x * y, 2) is acting as a filter.\n```\n\n\u003chr\u003e\n\n### Comprehension with binary strings.\n\nComprehension with binary is little different. You supposed to wrap inside `\u003c\u003c\u003e\u003e`\n\nLets check that…\n\n```elixir\niex\u003e b_string = \u003c\u003c\"blackode\"\u003e\u003e\n\"blackode\"\niex\u003e for \u003c\u003c x \u003c- b_string \u003e\u003e, do: x + 1\n'cmbdlpef'\n#here it is printing out the letter after every letter in the \"blackode\"\n```\n\nDid you observe that `x \u003c- b_string` is just changed something like `\u003c\u003c x \u003c- b_string \u003e\u003e` to make the sense.\n\n\u003chr\u003e\n\n### Advanced Comprehension IO.stream\n\nHere we are taking the elixir comprehension to the next level.  \nWe read the input from the keyboard and convert that to upcase and after that it should wait for another entry.\n\n```elixir\nfor x \u003c- IO.stream(:stdio, :line), into: IO.stream(:stdio, :line), do: String.upcase(x)\n```\n\nBasically `IO.stream(:stdio, :line)` will the read a line input from the keyboard.\n\n```elixir\niex\u003e for x \u003c- IO.stream(:stdio, :line), into: IO.stream(:stdio, :line), do: String.upcase(x)\nhello\nHELLO\nhi\nHI\nwho are you?\nWHO ARE YOU?\nblackode\nBLACKODE\n^c ^c # to break\n```\n\u003chr\u003e\n\n### Single Line Multiple module aliasing\n\nWe can also alias multiple modules in one line:\n\n```elixir\nalias Hello.{One,Two,Three}\n\n#The above line is same as the following \nalias Hello.One\nalias Hello.Two\nalias Hello.Three\n```\n\u003chr\u003e\n\n### Importing Underscore Functions from a Module\n\nBy default the functions with \\_ are not imported. However, you can do that by importing them with `:only` explicitly.\n\n```elixir\nimport File.Stream, only: [__build__: 3]\n```\n\u003chr\u003e\n\n### Extracting Project Information\n\n```elixir\nMix.Project.config[:version] # returns the version\nMix.Project.config[:app] # returns app name\n```\n\nYou have to be inside the `mix project` when you are trying. See this in action… [![asciicast](https://asciinema.org/a/g75QG1GmKR1Ret0PMThjxDd8u.png)](https://asciinema.org/a/g75QG1GmKR1Ret0PMThjxDd8u)\n\n\u003chr\u003e\n\n### Inner Binary Representation of String\n\nThis is a common trick in `elixir` . You have to concatenate the null byte `\u003c\u003c0\u003e\u003e` to a string that you want to see its inner binary representation like in the following way…\n\n```elixir\niex\u003e “hello” \u003c\u003e \u003c\u003c0\u003e\u003e\n\u003c\u003c104, 101, 108, 108, 111, 0\u003e\u003e\n```\n\u003chr\u003e\n\n### Multiple Bindings of a value\n\n```elixir\niex\u003e x = y = z = 5\n5\niex\u003e x\n5\niex\u003e y\n5\niex\u003e z\n5\n```\n\nSee this in action here...\n\n[![asciicast](https://asciinema.org/a/135066.png)](https://asciinema.org/a/135066)\n\n\u003chr\u003e\n\n### Not Null implementation in Structs\n\nThis is much like adding a not null constraint to the structs. When you try to define the struct with the absence of that key in the struct, it should raise an exception. Lets do that…  \nYou have to use `@enforce_keys [\u003ckeys\u003e]` while defining the struct…\n\n```elixir\n# Defining struct\ndefmodule Employee do\n   @enforce_keys [:salary]\n   defstruct name: nil, salary: nil\nend\n# Execution \niex\u003e employee = %Employee{name: \"blackode\"} # Error \niex\u003e employee = %Employee{name: \"blackode\",salary: 12345}\n%Employee{name: \"john\", salary: 12345}\n```\n\nSee this in action... [![asciicast](https://asciinema.org/a/dYmXUDeUoQ2gneSwM7tiIhbNE.png)](https://asciinema.org/a/dYmXUDeUoQ2gneSwM7tiIhbNE)\n\n**Warning** Keep in mind `@enforce_keys` is a simple compile-time guarantee to aid developers when building structs. It is not enforced on updates and it does not provide any sort of value-validation. The above warning is from the [ORIGINAL DOCUMENTATION](https://hexdocs.pm/elixir/Kernel.html#defstruct/1-enforcing-keys)\n\n\u003chr\u003e\n\n### Check Whether Function is Exported or not\n\nElixir provides `function_exported?/3` to achieve this…\n\n```elixir\n# Defining the module with one exported function and private one\ndefmodule Hello do\n  def hello name do\n   IO.puts name\n  end\n  defp hellop name do\n    IO.puts name \n  end\nend\n# Execution Copy and paste above lines of code in iex\u003e \niex\u003e function_exported? Hello, :hello,1\ntrue\niex\u003e function_exported? Hello, :hellop, 1\nfalse\n```\n\nSee this in action... [![asciicast](https://asciinema.org/a/135080.png)](https://asciinema.org/a/135080)\n\n\u003chr\u003e\n\n### Splitting the string with multiple Patterns\n\nWe all know how to split a string with `String.split/2 function`. But you can also pass a **pattern** to match that over and over and splitting the string whenever it matches the **pattern**.\n\n```elixir\n\"Hello Blackode! Medium-is-5*\"\n```\n\nIf you observe the above string, it comprises of **two blank spaces** , **one exclamation mark** `!` , **two minus — symbols** `-` and a **asterisk** `*` symbol. Now we are going to split that string with all of those.\n\n```elixir\nstring = \"Hello Blackode! Medium-is-5*\"\nString.split string, [\" \", \"!\", \"-\", \"*\"]\n#output\n[\"Hello\", \"Blackode\", \"\", \"Medium\", \"is\", \"5\", \"\"]\n```\n\nThe pattern is generated at run time. You can still validate with `:binary.compiled`\n\n\u003chr\u003e\n\n### Checking the closeness of strings\n\nYou can find the distance between the two strings using `String.jaro_distance/2`. This gives a float value in the range `0..1` Taking the `0` for no close and `1` is for exact closeness.\n\n```elixir\niex\u003e String.jaro_distance \"ping\", \"pong\"\n0.8333333333333334\n\niex\u003e String.jaro_distance \"color\", \"colour\"\n0.9444444444444445\niex\u003e String.jaro_distance \"foo\", \"foo\"\n1.0\n```\n\nFor the **FUN**, you can find your closeness with your name and your partner or lover in case if aren’t married. Hey… ! I am just kidding…. It is just an algorithm which is predefined where our love is undefined. Cheers …….. :\\)\n\n\u003chr\u003e\n\n### Executing code Immediately after loading a Module\n\nElixir provides `@on_load` which accepts `atom` as function name in the same module or a `tuple` with function\\_name and its arity like `{function_name, 0}`.\n\n```elixir\n#Hello module \ndefmodule Hello do\n@on_load :onload     # this executes after module gets loaded \n  def onload do\n    IO.puts \"#{__MODULE__} is loaded successfully\"\n  end\nend\n# Execution .... Just copy and paste the code in the iex terminal\n# You will see the output something like this ....\nElixir.Hello is loaded successfully  \n{:module, Hello,\n \u003c\u003c70, 79, 82, 49, 0, 0, 4, 72, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 130,\n   0, 0, 0, 12, 12, 69, 108, 105, 120, 105, 114, 46, 72, 101, 108, 108, 111, 8,\n   95, 95, 105, 110, 102, 111, 95, 95, 9, ...\u003e\u003e, {:onload, 0}}\n```\n\nYou can see this in live here… [![asciicast](https://asciinema.org/a/GGmD9jUuRQQNherMh3fY5Zn4e.png)](https://asciinema.org/a/GGmD9jUuRQQNherMh3fY5Zn4e)\n\n\u003chr\u003e\n\n### Chain of \\[ or \\] ’ s  in guard clauses with when\n\nThis is about multiple guards in the same clause and writing `or` conditions with out using `or` We all know that `or` is used as a conjunction for two conditions resulting true if either one of them is true. Many of us writing the or conditions in the guard as following way…\n\n```elixir\ndef print_me(thing) when is_integer(thing) or is_float(thing) or is_nil(thing), do: \"I am a number\"\n```\n\nYou can also do this in bit more clear format as the following way…\n\n```elixir\ndef print_me(thing)\n  when is_integer(thing)\n  when is_float(thing)\n  when is_nil(thing) do\n \"I am a number \"\nend\n```\n\nSee this in action… [![asciicast](https://asciinema.org/a/S64h7ydwzfMXsPgOeSfcRXejA.png)](https://asciinema.org/a/S64h7ydwzfMXsPgOeSfcRXejA)\n\nSee also [Elixir Style Guide](https://github.com/christopheradams/elixir_style_guide)\n\n\u003chr\u003e\n\n### Prett Printing of a quoted Expression\n\n#### Macro.to\\_string \\|\u0026gt; IO.puts\n\nIn general, when you pass the quote expression to `Macro.to_string` , it returns the actual code in a string format and we all knew this.\n\nThe weird thing is, it gives the output in a single line along with **\\n** characters inside the string.\n\nCheck it down\n\n```elixir\n    iex(2)\u003e q = quote do\n    ...(2)\u003e 1+2\n    ...(2)\u003e name = \"blackode\"\n    ...(2)\u003e end\n\n    {:__block__, [],\n     [\n       {:+, [context: Elixir, import: Kernel], [1, 2]},\n       {:=, [], [{:name, [], Elixir}, \"blackode\"]}\n     ]}\n\n    iex(3)\u003e Macro.to_string q\n    \"(\\n  1 + 2\\n  name = \\\"blackode\\\"\\n)\"\n```\n\nTo print the new lines, you pipe the string output from `Macro.to_string` to `IO.puts` like in the following code snippet. It gives the clean output by printing in new line.\n\n```elixir\n    iex(4)\u003e Macro.to_string(q) |\u003e IO.puts\n    (\n      1 + 2\n      name = \"blackode\"\n    )\n    :ok\n```\n\n![](https://cdn-images-1.medium.com/max/2000/1*dZ3sOdnXY2Ra7onjxW-0lA.png)\n\n#### Check this in live\n\n[![asciicast](https://asciinema.org/a/161913.png)](https://asciinema.org/a/161913)\n\n\u003chr\u003e\n\n### Finding the loaded files in iex and dynamic loading files on-fly\n\n1. **Finding the loaded files**\n\n#### Code.loaded\\_files\n\nIn elixir, we are having a definition `loaded_files` in the module `Code` used to find the loaded files.\n\nLet’s see this.\n\nRun the command `iex` inside your terminal and call the function `Code.loaded_files` .\n\nIt gives an empty list `[]` as output because we haven’t loaded any files so far.\n\n```elixir\n    $ iex\n    iex\u003e Code.loaded_files\n    []\n```\n\n\u003chr\u003e\n\n#### File Loading\n\nLet’s create a file `hello.ex` with a single function definition `hello` which just prints a string **“Welcome to the world”** for the demo purpose.\n\n```elixir\n    # hello.ex\n\n    defmodule Hello do\n      def hello do\n        IO.puts \"Welcome to the world\"\n      end\n    end\n```\n\nSave the file after editing.\n\nNow, make sure you are in the same directory of where the file exists and run the command\n\n```elixir\n    $ iex hello.ex\n```\n\nIt opens the **Elixir** interactive shell by loading the `hello.ex` file as well.\n\nNow, you can see the loaded file by calling `Code.loaded_files` . It outputs the path to the file.\n\n```elixir\n    iex\u003e Code.loaded_files\n    [\"/home/john/hello.ex\"]\n```\n\nThat is one way of loading files. You can also load them on-fly in `iex session`\n\n\u003chr\u003e\n\n#### Dynamic loading on-fly\n\n**Code.load\\_file/1**\n\nUnlike loading files with `iex hello.ex` , you can load them on-fly in `iex`session with the help of `Code.load_file \"path/to/file\"` .\n\nLet us assume that we have a file `hello.ex` in our current directory and open `iex` session from the same directory.\n\n```elixir\n    $ iex\n\n    iex\u003e Code.load_file \"hello.ex\"\n    [\n      {Hello,\n       \u003c\u003c70, 79, 82, 49, 0, 0, 4, 72, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 140,\n         0, 0, 0, 15, 12, 69, 108, 105, 120, 105, 114, 46, 72, 101, 108, 108, 111,\n         8, 95, 95, 105, 110, 102, 111, 95, 95, 9, ...\u003e\u003e}\n    ]\n```\n\n#### Let's check this in action\n\n[![asciicast](https://asciinema.org/a/161920.png)](https://asciinema.org/a/161920)\n\n\u003chr\u003e\n\n### Making Providing deprecation reason \n\n**@deprecated**\n\nYou might be noticed the warnings of using deprecated functions in a library along with some useful hint text. Today, we build this from scratch.\n\nSuppose, you have written a library and want to update the name of one function in your next build release and if the user tried to access the old function then you have to warn him of using deprecated function instead of updated one.\n\nTo see this in action, you need to create new mix project.\n\nLet’s do that.\n\n```elixir\n    mix new hello\n```\n\nNext change the directory to the project created.\n\n```elixir\n    cd hello\n```\n\nNow, edit the file `lib/hello.ex` in the project with the following code\n\n```elixir\n    #lib/hello.ex\n\n    defmodule Hello do\n      def hello do \n        Printee.print()\n      end\n    end\n\n    defmodule Printee do\n\n      @deprecated \"print/0 is deprecated use show/0\" \n      def print do\n        IO.puts \"hello blackode\"\n      end\n\n      def show do\n        IO.puts \"hello blackode\"\n      end\n\n    end\n```\n\n![](https://cdn-images-1.medium.com/max/2000/1*n0RNxQCvWwy3ZQeIKeG_ZQ.png)\n\nThis file comprises of two modules `Hello` and `Printee` . The `Printee` module comprises of two functions `print/0` and `show/0` . Here purposely, `print/0` is considered as a deprecated function used inside the `Hello` module.\n\nThe mix compiler automatically looks for calls to deprecated modules and emit warnings during compilation.\n\nSo, when you compile the project `mix compile`, it gives a warning saying\n\n\u003e **“print/0 is deprecated use show/0”**\n\nlike in the following screenshot.\n\n Deprecated Function Warning\n\n![image](https://cdn-images-1.medium.com/max/2000/1*iF5ROIflyq_UPuNJBtTrHA.png)\n\n#### Check the live coding\n\n[![asciicast](https://asciinema.org/a/161939.png)](https://asciinema.org/a/161939)\n\n\n\u003chr\u003e\n\n### Module Creation with create function\n\n#### Module.create/3\n\nAs we all know `defmodule` is used to create a module. In similar, `Module.create/3` is also used to create a module.\n\nThe only difference in defining a module with `Module.create/3` is the definition inside the module is quoted expression.\n\nHowever, we can use the help of `quote` to create a quoted expression.\n\nWe have to pass three parameters to `Moduel.create` .\n\nThe first one is **name** of the module. The second one is module definition in quoted expression. The third one is location. The location is given in `keyword list` like `[file: String.t, line: Integer ]` or else you can just take the help of `Macro.Env.location(__ENV__)` which returns the same.\n\n![image](https://cdn-images-1.medium.com/max/2000/1*nXADw371CsJkTGlkWoXVYw.png)\n\nlocation of loc\n\n```elixir\n    iex\u003e module_definition = quote do: def hello, do: IO.puts \"hello\"\n```\n\nThe above line of code gives the context of the module definition and collected in `module_definition` . We can use this `module_defintion` to pass as second parameter to `Module.create/3` function.\n\n module definition context\n\n![image](https://cdn-images-1.medium.com/max/2000/1*w1vIuGh7xfyLkUq_-odq4w.png)\n\nLet’s put all together and see the magic\n\n```elixir\n    iex(8)\u003e Module.create Hello, module_definition, [file: \"iex\", line: 8 ]\n```\n\n![image](https://cdn-images-1.medium.com/max/2000/1*Or7UIFfZ0Vw8MjqiffM51w.png)\n\nCreating another module `Foo` with same module function\n\n```elixir\n    iex(10)\u003e Module.create Foo, module_definition, Macro.Env.location(__ENV__)\n```\n\n![image](https://cdn-images-1.medium.com/max/2000/1*UtnhjKAKmJ5pCKy-BhJBUA.png)\n\n#### Check out the live execution\n\n[![asciicast](https://asciinema.org/a/162255.png)](https://asciinema.org/a/162255)\n\n\u003chr\u003e\n\n### Finding the list of bound values in iex\n\n#### binding\n\n```elixir\n    iex\u003e binding\n    []\n    \n    iex\u003e name = \"blackode\"\n    \"blackode\"\n    \n    iex\u003e blog = \"medium\"\n    \"medium\"\n    \n    iex\u003e binding\n    [blog: \"medium\", name: \"blackode\"]\n```\n\n![image](https://cdn-images-1.medium.com/max/2000/1*HWgNsJ7k0beakedw-Z_XeQ.png)\n\nThis is used in debugging purpose inside the function.\n\nIt is also very common to use `IO.inspect/2` with `binding()`, which returns all variable names and their values:\n\n```elixir\ndef fun(a, b) do\n  IO.inspect binding()\n  ...\nend\n```\n\nWhen `fun/2` is invoked with `:laughing`, `\"time\"` it prints:\n\n```elixir\n[a: :laughing, b: \"time\"]\n```\n\nYou can also give context to the `binding`\n\nIf the given context is **nil \\***\\(by default it is\\), \\*the binding for the current  \n context is returned.\n\n```elixir\n    iex\u003e var!(x, :foo) = 1\n    1\n    iex\u003e binding(:foo)\n    [x: 1]\n```\n\n#### Check out the live execution\n\n[![asciicast](https://asciinema.org/a/162257.png)](https://asciinema.org/a/162257)\n\n\u003chr\u003e\n\n### Fun with Char\\_Lists\n\nWe can convert any integer to charlist using `Integer.char_list` . It can be used in two ways either passing the base the base value or not passing.\n\nLet’s try with base and with out base.\n\n#### without base\n\n```elixir\n    iex\u003e Integer.to_charlist(882681651)\n    '882681651'\n```\n\n#### with base\n\n```elixir\n    iex\u003e Integer.to_charlist(882681651, 36)\n    'ELIXIR'\n```\n\nTry your own names as well and find your value with base\n\n```elixir\n    iex\u003e List.to_integer 'BLACKODE', 36\n    908344015970\n\n    iex\u003e Integer.to_charlist(908344015970, 36)\n    'BLACKODE'\n```\n\u003chr\u003e\n\n### Universal Code base formatter\n\nCode formatting is easy now with the help of mix task `mix format`. It will take care of all you care about cleaning and refactoring as well. It can assure a clean code base or simply universal code base which maintains some useful standards. This really saves a lot of time.\n\n```elixir\n    mix format filename\n```\n\nTo know more about the codebase formatting, check out my recent article on\n\n#### \\[Code Formatter The Big Feature in Elixir\n\n1.6\\]\\([https://medium.com/blackode/code-formatter-the-big-feature-in-elixir-v1-6-0-f6572061a4ba](https://medium.com/blackode/code-formatter-the-big-feature-in-elixir-v1-6-0-f6572061a4ba)\\)\n\nwhich explains all about using `mix format` task and its configuration in detail with screen shots of vivid examples.\n\n\u003chr\u003e\n\n### Replacing a Key in Map\n\nI know, you might be thinking why some one would do that. I too had the same feeling until I met with a requirement in one of my previous projects where I was asked to replace `address1` with `address` and some other keys as well. It is a huge one. I have to do change many keys as well.\n\nI’m here with a simple `map` to keep it understandable. But, the technique is same.\n\n\u003e The thing to remember is; be smart and stay long;\n\n```elixir\ndetails = %{name: \"john\", address1: \"heaven\", mobile1: \"999999999\"}\n```\n\nThe above map comprises of **two** weird keys address1 and mobile1 where we do workout on to take over them.\n\n```elixir\niex\u003e details = %{name: \"john\", address1: \"heaven\", mobile1: \"999999999\"}\n%{address1: \"heaven\", mobile1: \"999999999\", name: \"john\"}\n\niex\u003e Map.new(details, fn  \n  {:address1, address} -\u003e {:address, address}\n  {:mobile1, mobile} -\u003e {:phone, mobile} \n  x -\u003e x \nend)\n\n%{address: \"heaven\", name: \"john\", phone: \"999999999\"} #output\n```\n\n#### What’s the magic here❓\n\nNothing , just pattern\\_matching, the boon for functional programmers. The magic lies inside Map.new and the **anonymous** function where we used our **magic band** to see the actual **logic**.\n\n![](https://cdn-images-1.medium.com/max/3816/1*rlUV3ulHJ_VN7bsOTsVi3A.png)\n\n## Filtering With match?\n\nAs we know, `Enum.filter` will do the job based on the evaluation of a condition. But still, we can use the **pattern** to **filter** things.\n\nLet me make you clear with the following example.\n\nI have a list of **users** where their names are mapped to their preferred programming language.\n\n```elixir\niex\u003e user_and_programming_languages = \n %{john: \"elixir\", latha: \"elixir\", hari: \"erlang\", toy: \"perl\"}\n\n%{hari: \"erlang\", john: \"elixir\", latha: \"elixir\", toy: \"perl\"}\n```\n\nLike above, the **user\\_names** are mapped with their **languages**. Now, our job is to filter the _**users**_ of **elixir** language.\n\nJust let me know which one you do prefer after checking out the following…\n\n```elixir\niex\u003e user_and_programming_languages |\u003e\nEnum.filter(fn {_, lang} -\u003e lang==\"elixir\" end )\n\n[john: \"elixir\", latha: \"elixir\"]  \n#output\n```\n\nOR, using match? for pattern based\n\n```elixir\nuser_and_programming_languages = \n %{john: \"elixir\", latha: \"elixir\", hari: \"erlang\", toy: \"perl\"}\n\nuser_and_programming_languages |\u003e\nEnum.filter(\u0026match?({_, \"elixir\"}, \u00261) )\n\n[john: \"elixir\", latha: \"elixir\"]  \n#output\n```\n\nCheckout the screenshots of _evaluation_\n\n![](https://cdn-images-1.medium.com/max/3830/1*AAW1xh_NrmGCxWWZPM3eAw.png)\n\n![](https://cdn-images-1.medium.com/max/3844/1*yLgMcHqdSgWhNQFhXqjXgw.png)\n\nI took the simpler lines of code to give a demo of using match? but, it’s usages are limit less. Just think about the **pattern** and match over it. Think out of the box guys. But don’t blow up your mind and don’t blame me for that.\n\n**Warning: ⚠️**\n\nMake sure of your **pattern** as the **first** parameter to the match? otherwise, you have to pay for the compiler. Just kidding 😃\n\n```elixir\niex\u003e user_and_programming_languages |\u003e\nEnum.filter(\u0026match?(\u00261, {_, \"elixir\"},) )\n```\n\n![](https://cdn-images-1.medium.com/max/3838/1*OWhJ_6CgVOr42-7vvyXWJg.png)\n\n\n\u003chr\u003e\n\n### Bangpipe \u0026lt;\\|\u0026gt; Left and Right\n\nAs we know elixir is free language, where you can build anything you need. But, be careful It is just to show you something is achievable.\n\nIt is a **LEFT** and **RIGHT** Pipe\n\nWe usually end up with some sort of results in the format {:ok, result} . This can be found anywhere in your project sooner or later.\n\nIf you pipe it to the function obviously you will end up with an unknown expectation. I am talking about run-time errors. Our \\|\u0026gt; is not smart enough to check it for whether is a direct result or {:ok, result} .\n\nLet’s build it for the **GOD** sake but not for your **client**.\n\n⚠️ _**Don’t use this ever and don’t do write macros until you write new framework.**_\n\n```elixir\niex\u003e defmodule Bangpipe do\n  defmacro left \u003c|\u003e right do\n    quote do\n      unquote(left)\n      |\u003e case do\n        {:ok, val} -\u003e val \n        val -\u003e val\n      end\n      |\u003e unquote(right)\n    end\n  end\nend\n```\n\nThis Bangpipe I mean \u0026lt;\\|\u0026gt; is defined to do the task. Before sending the result to the function in right, it is performing the pattern matching over the result to identify what kinda result it is. I hope you understood what actually the result I am talking about. [**The Secret behind Elixir Operator Re-Definitions : + to -** \\*Just for Fun](https://medium.com/blackode/the-secret-behind-elixir-operator-overriding-to-a564fd6c0dd6)\\*\n\nWe can also do re definitions on elixir operators. Check above URL.\n\nHow to use ❓\n\nJust import **Bangpipe** the left-right pipe will be loaded. Copy and paste to experience it in live and fast into iex\n\n```elixir\niex[6]  import Bangpipe\nBangpipe\n\niex[7]  data = {:ok, [1,2,3,4,5]} \n{:ok, [1, 2, 3, 4, 5]}\n\niex[8]  data \u003c|\u003e length\n5\n```\n\n\u003e “Good programmers write the code \u0026 great programmers steal the code” This tip is copied from the [Elixir Lightening Talk](https://www.youtube.com/watch?v=2vocLGYFj8Q\u0026t=25s)\n\n**\\*Bangpipe** **\u0026lt;\\|\u0026gt;** **execution\\***\n\n![\\*\\*Bangpipe\\*\\* \\*\\*\u0026amp;lt;\\|\u0026amp;gt;\\*\\* \\*\\*execution\\*\\*](https://cdn-images-1.medium.com/max/3820/1*FDNBw77-79TpQNyoqphuZw.png)\n\n\u003chr\u003e\n\n### Finding the function callers in a project.\n\n_Let’s create a brief story here._\n\nThe moment when GOD’S against you, your manager will come and give you a vast legacy project code and asked you to find out _**all the places where a particular function**_ is called. In a sentence, the **callers** of a particular function.\n\n**What will you do?** I don’t think it is a smart way of surfing in each and every file. I don’t. So, you don’t.\n\n```elixir\nmix xref callers Module.function\n\nexample\n\nmix xref callers Poison.decode\n```\n\nPrints all callers of the given **CALLEE**, which can be one of: **Module**, **Module.function**, or **Module.function/arity**.\n\n### Examples:\n\n```elixir\nmix xref callers ***Module***\nmix xref callers ***Module.fun***\nmix xref callers ***Module.fun/3***\n```\n\n_mix xref callers Poison.decode_\n\n![mix xref callers Poison.decode](https://cdn-images-1.medium.com/max/3818/1*5pDTNeE2I0lrqBlR18inOQ.png)\n\nYou can add function arity to be more specific, in this case mix xref callers Poison.decode/1 .\n\n**BOOM !** Now, you can surprise the manager with results before he reaches his cabin. Be fast and smart.\n\nI solely experienced this when my co-worker I better say **co-programmer** asked for help regarding the situation but there's no manager in my case.\n\nExplore more about **xref**\n\n```elixir\nmix help **xref**\n```\n\u003chr\u003e\n\n### Using Enum.group_by beyohnd Grouping of things\n\nI have a collection of hotel\\_bookings and I need to group them based on their booking status.\n\nTo keep this simple, I am just using some false random collection.\n\n```elixir\niex\u003e hotel_bookings = [ \n%{name: \"John\", country: \"usa\", booking_status: :success},\n%{name: \"Hari\", country: \"india\", booking_status: :fail},\n%{name: \"Mahesh\", country: \"austria\", booking_status: :pending},\n%{name: \"Ruchi\", country: \"paris\", booking_status: :success},\n%{name: \"Nitesh\", country: \"malasia\", booking_status: :success},\n%{name: \"Manoj\", country: \"japan\", booking_status: :fail},\n%{name: \"Akhilesh\", country: \"china\", booking_status: :pending},\n%{name: \"Rajesh\", country: \"india\", booking_status: :fail},\n%{name: \"Payal\", country: \"london\", booking_status: :success},\n%{name: \"Kumar\", country: \"france\", booking_status: :fail}\n]\n```\n\nLet’s group the things.\n\n```elixir\niex\u003e Enum.group_by(hotel_bookings, \u0026Map.get(\u00261, :booking_status))\n%{\n  fail: [\n    %{booking_status: :fail, country: \"india\", name: \"Hari\"},\n    %{booking_status: :fail, country: \"japan\", name: \"Manoj\"},\n    %{booking_status: :fail, country: \"india\", name: \"Rajesh\"},\n    %{booking_status: :fail, country: \"france\", name: \"Kumar\"}\n  ],\n  pending: [\n    %{booking_status: :pending, country: \"austria\", name: \"Mahesh\"},\n    %{booking_status: :pending, country: \"china\", name: \"Akhilesh\"}\n  ],\n  success: [\n    %{booking_status: :success, country: \"usa\", name: \"John\"},\n    %{booking_status: :success, country: \"paris\", name: \"Ruchi\"},\n    %{booking_status: :success, country: \"malasia\", name: \"Nitesh\"}, \n    %{booking_status: :success, country: \"london\", name: \"Payal\"}\n  ]\n}\n```\n\nThis is well and good but I need only name in the list instead of map. I mean some thing like %{fail: \\[\"Hari\", \"Manoj\"\\], ...}\n\nWe just need to tell the group\\_by what to return in return of grouping\n\n```elixir\niex\u003e  Enum.group_by(hotel_bookings, \u0026Map.get(\u00261, :booking_status), \u0026Map.get(\u00261, :name))\n%{\n  fail: [\"Hari\", \"Manoj\", \"Rajesh\", \"Kumar\"],\n  pending: [\"Mahesh\", \"Akhilesh\"],\n  success: [\"John\", \"Ruchi\", \"Nitesh\", \"Payal\"]\n}\n```\n\n\u003chr\u003e\n\n###  Running only failed tests \n\n```elixir\nmix test --failed\n```\n\n\u003chr\u003e\n\n### Inspecting Only Derived Elements in Structs\n\nWe can limit the keys to print while we **inspect** structs using `@derive` attribute.       \n\nDon’t believe, check it down\n\n```elixir\ndefmodule Address do  \n\t@derive {Inspect, only: [:name, :country]}  \n\tdefstruct [name: \"john\", street: \"2nd lane\", door_no: \"12-3\", state: \"mystate\", country: \"My Country\"  ]\nend\n\niex\u003e %Address{}\n#Address\u003ccountry: \"My Country\", name: \"john\", ...\u003e  #OUTPUT\n```\n\n\u003chr\u003e\n\n### Enumeration \u0026 Merging two maps\n\nLet’s  consider we have a requirement to modify a map and need to merge the  modified map with some other map. **API** developers always face this  situation like modifying the response according to the client.\n\nConsider the following two maps **user** and **location**\n\n```elixir\nuser = %{name: \"blackode\", publication: \"medium\", age: 25}\nlocation = %{latitude: 38.8951, longitude:  -77.0364}\n```\n\nNow, we have a requirement to modify the keys for **location** map from `latitude` to `lat` and `longitude` to `long`. After **map** modification, the **modified map** has to merge into **user** map.\n\nJust to convey the idea, I am using a map with fewer number of key-value pairs.\n\nBefore, I was doing `Enum.map/2` followed by `Enum.into/2` followed by `Map.merge/2`\n\n#### Don’t Do\n\n```elixir\nlocation\n|\u003e Enum.map(fn {:latitude, lat} -\u003e {:lat, lat}\n               {:longitude, long} -\u003e {:long, long} \n   end)\n|\u003e Enum.into(%{}) #as map gives keyword list\n|\u003e Map.merge(user)\n```\n\n![img](assets/images/elixir-tips-9/1_o_vD912B8lmsB5ShQV4r7Q.png)\n\nWe can simply achieve this using alone `Enum.into/3`\n\n#### Do\n\n```elixir\nEnum.into(location, user, fn \n  {:latitude, lat} -\u003e {:lat, lat}\n  {:longitude, long} -\u003e {:long, long} \nend)\n```\n\n![img](assets/images/elixir-tips-9/1_NK77RCY7txKVz1GABKTCfg.png)\n\n\u003chr\u003e\n\n### Finding System Schedulers available count\n\n```elixir\nSystem.schedulers\n```\n\nYou can also check **online** schedulers like\n\n```elixir\nSystem.schedulers_online\n```\n\nYou can type in your terminal not iex print the number of processing units available using the command `nproc`\n\n```bash\n$ nproc\n```\n\n![img](assets/images/elixir-tips-9/1_ppPYT6DiXR3Z3TVkefiH-w.png)\n\n\u003chr\u003e\n\n### Finding Message Queue Length of a Process\n\nWe can know queue length of a process using `Process.info/2`\n\n```elixir\nProcess.info(pid, :message_queue_len)\n```\n\nLet’s check that\n\n```elixir\niex\u003e send self, :hello\niex\u003e send self, :hi\n```\n\nAbove lines will send two messages to the current process. As we did not  write any receive block here, they keep waiting inside mailbox queue.\n\nNow we will check the messages queue length of the current process `self`\n\n```elixir\niex\u003e Process.info(self, :message_queue_len)\n{:message_queue_len, 2}\n```\n\n![img](assets/images/elixir-tips-9/1_nDTqT7HYzKw5imFoSbPCRw.png)\n\nNow we handle one message using receive block and will check the queue length once again.\n\n```elixir\niex\u003e receive do: (:hello -\u003e \"I GOT HELLO\")\n\"I GOT HELLO\"\n\niex\u003e Process.info(self, :message_queue_len)\n{:message_queue_len, 1}\n```\n\nDid you see that, we have only one message in queue as we handled `:hello` message.\n\nAgain, we handle the left over message `:hi` and this time the length will be `0` Of course it will be as there are no more messages to handle.\n\n```elixir\niex\u003e receive do: (:hi -\u003e \"I GOT HI\")\n\"I GOT HI\"\n\niex\u003e Process.info(self, :message_queue_len)\n{:message_queue_len, 0}\n```\n\n![img](assets/images/elixir-tips-9/1_2Hx-vUT40ghdkPm7Sj9vEg.png)\n\n\n\nhttps://asciinema.org/a/271142?source=post_page-----7155532befd7----------------------\n\n\u003chr\u003e\n\n### Loading project Module aliases (.iex.exs)\n\nWe always try to execute the project module functions in `iex` interactive shell to check its behavior.\n\nSometimes, our module names will be lengthy to type. Of course, we can type `alias` in `iex` but it vanishes every time you restart the `iex` shell and you have to type the aliases once again.\n\nCreate `.iex.exs` file in the project root directory and add all **aliases** to the file.\n\nWhenever you start `iex` shell, it looks for `.iex.exs` file in the current working folder . So, it creates all the **aliases** in the `.iex.exs` file.\n\nIf file isn’t exist in the current directory, then it looks in your **home** directory i.e `~/.iex.exs`.\n\n![img](assets/images/elixir-tips-9/1_TaWgvSn-6HbYGS_Cu3Vsdg.png)\n\n\u003chr\u003e\n\n### Finding N slowest tests in mix application\n\n```elixir\nmix test --slowest N  # N is integerexamplemix test --slowest 3\n```\n\nReplace `N` with any integer value then it prints timing information for the N slowest tests.\n\nIt automatically adds`--trace` and`--preload-modules`\n\n\u003chr\u003e\n\n### Re-Designing Custom data type inspection across the app\n\nIt is simply implementing **Inspect** protocol for our custom type.\n\nWe can re design the inspect output for any specific type by implementing the Inspect protocol and overriding inspect function.\n\n\n\n```elixir\ndefmodule Student do  \n  defstruct name: \"John\", place: \"Earth\"\nend\n\ndefimpl Inspect, for: Student do\n  def inspect(student, _opts) do\n    \"\"\"\n    -----------|---------------------\n       Name    :     #{student.name} \n    -----------|---------------------\n       Place   :     #{student.place}\n    -----------|---------------------\n    \"\"\"\n  end\nend\n\niex\u003e %Student{}\n-----------|---------------------\n   Name    :     John \n-----------|---------------------\n   Place   :     Earth\n-----------|---------------------\n```\n\n\n\nIt is highly useful for custom structs where we can define what we need to see whenever we inspect our struct.\n\n\u003chr\u003e\n\n### Writable Temporary Directory\n\nIt is trivial that we need a temporary directory to write certain files and to delete later based on our code logic.\n\nIn elixir, we can get the path based on the operating system the app is running using `System.tmp_dir/0` which returns a writable temporary directory.\n\nWe can customize the path with different environment variables like in the following;\n\n```elixir\nexport TMP=\"~/tmp\"\niex\niex\u003e System.tmp_dir\n```\n\nIt returns the directory set to **TMP** environment variable if available\n\n```elixir\nexport TMPDIR=\"~/temp\"\niex\niex\u003e System.tmp_dir\n```\n\nIt returns the directory set to **TMPDIR** environment variable if available\n\nIf three environment variables are set, then it searches for directories in the following order\n\n```\n1. TMPDIR\n2. TEMP\n3. TMP\n```\n\nIf none of them was found then it returns default directories based on the operating system like `C:\\TMP` on **Windows** or `/tmp`on **Unix**\n\nIn case the default directories are not found then it returns PWD i.e present working directory as a last piece of cake.\n\n## WARNING\n\nThough you exported **Environmental** variables, it still gives default values if those exported directories are not available.\n\n\n\n\n## Note\n\nCheck out our Medium Publication\n\n[![Medium Blog Image](.gitbook/assets/medium_blog.jpg)](https://medium.com/blackode)\n\nIf you wish to join our telegram channel, here it is\n\n[![Telegram Blog Image](.gitbook/assets/telegram_channel.png)](https://t.me/blackoders)\n\n## How to contribute ?\n\nContribute to `Part-9` creating a new branch `Part-9` and make a pull request with atleast 3 Unique tips.\n\n### Thanks for Reading.\n\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --\u003e\n\u003c!-- prettier-ignore-start --\u003e\n\u003c!-- markdownlint-disable --\u003e\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://blackode.in\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/9107477?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eAnkanna\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=blackode\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=blackode\" title=\"Tests\"\u003e⚠️\u003c/a\u003e \u003ca href=\"#infra-blackode\" title=\"Infrastructure (Hosting, Build-Tools, etc)\"\u003e🚇\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/progsmile\"\u003e\u003cimg src=\"https://avatars3.githubusercontent.com/u/6272773?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eDenis Klimenko\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=progsmile\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=progsmile\" title=\"Documentation\"\u003e📖\u003c/a\u003e \u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Aprogsmile\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"http://www.techgaun.com\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/1886670?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eSamar Dhwoj Acharya\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Atechgaun\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://praveenperera.com\"\u003e\u003cimg src=\"https://avatars0.githubusercontent.com/u/1775346?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003ePraveen Perera\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Apraveenperera\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"http://leandrocp.com.br\"\u003e\u003cimg src=\"https://avatars3.githubusercontent.com/u/36407?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eLeandro Cesquini Pereira\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=leandrocp\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"http://remoter.net\"\u003e\u003cimg src=\"https://avatars1.githubusercontent.com/u/8299599?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eMaxim Dzhuliy\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Amax-si-m\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/evnu\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/224554?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eMagnus\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=evnu\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/eksperimental\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/9133420?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eEksperimental\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Aeksperimental\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"http://syntazo.com\"\u003e\u003cimg src=\"https://avatars3.githubusercontent.com/u/38292?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003ethanos vassilakis\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Athanos\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/gmsecrieru\"\u003e\u003cimg src=\"https://avatars0.githubusercontent.com/u/190883?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eGeorge Secrieru\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Agmsecrieru\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://erick.navarro.io\"\u003e\u003cimg src=\"https://avatars3.githubusercontent.com/u/862022?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eErick Navarro\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=erickgnavar\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://twitter.com/irisTa56\"\u003e\u003cimg src=\"https://avatars1.githubusercontent.com/u/27466252?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eTakayuki Kobayashi\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=irisTa56\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=irisTa56\" title=\"Tests\"\u003e⚠️\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://vasuadari.com\"\u003e\u003cimg src=\"https://avatars1.githubusercontent.com/u/3678553?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eVasu Adari\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=vasuadari\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/maximemenager\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/43468959?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003emaximemenager\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=maximemenager\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Amaximemenager\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://blog.tt67wq.top/\"\u003e\u003cimg src=\"https://avatars3.githubusercontent.com/u/12907812?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003ett67wq\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Att67wq\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e \u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=tt67wq\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://wildanfathan.com\"\u003e\u003cimg src=\"https://avatars3.githubusercontent.com/u/10251361?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eWildan Fathan\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/issues?q=author%3Af4th4n\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e \u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=f4th4n\" title=\"Documentation\"\u003e📖\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/rodesousa\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/8577532?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003erodesousa\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/blackode/elixir-tips/commits?author=rodesousa\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n\u003c!-- markdownlint-restore --\u003e\n\u003c!-- prettier-ignore-end --\u003e\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:END --\u003e\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n\n\u003cdiv\u003e\n\t\u003ca href=\"https://www.buymeacoffee.com/blackode\" target=\"_blank\"\u003e\u003cimg src=\"https://cdn.buymeacoffee.com/buttons/arial-green.png\" alt=\"Buy Me A Coffee\" style=\"height: 51px !important;width: 217px !important;\" \u003e\u003c/a\u003e\n\t\u003c/div\u003e\n","funding_links":["https://www.buymeacoffee.com/blackode"],"categories":["Uncategorized","CSS"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblackode%2Felixir-tips","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fblackode%2Felixir-tips","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblackode%2Felixir-tips/lists"}