Hexa's Blog

Elixir Cheatsheet

20/11/2015 cheatsheet

This is cheatsheet for Elixir, it’s a not a summary of this language, this article all about tweak, remember note for Elixir language.

1. For loop Given that, we we a list of map

people = [
  %{name: "Linh", age: 22},
  %{name: "Son", age: 18},
  %{name: "Long", age: 15},
]
for person <- people, do: (
  IO.inspect person
)

Elixir supports a for conditional loop.

for person = %{age: tuoi}<- people, tuoi < 20, do: (
  IO.inspect person
)

2. Update a map

old_map = %{attr1: 1, attr2: 2 }
new_map = %{old_map | attr1:  3}

3. Struct Generate Struct

defmodule Subscriber do
  defstruct name: "", paid: false, over_18: true
end

sub1 = %Subcriber{}
sub2 = %Subcriber{name: "sub2", paid: true, over_18: false}

Use Struct attribute

sub1.name
sub2.name
sub2[:name]

Update attr in a struct

sub2 = %Subcriber{name: "sub2", paid: true, over_18: false}
sub2 = %{sub2 | name: "Another sub2"}

#alternative solution:
put_in(sub2.name, "new_name")