Skip to content

Instantly share code, notes, and snippets.

View BrooklinJazz's full-sized avatar

Brooklin Myers BrooklinJazz

View GitHub Profile
@BrooklinJazz
BrooklinJazz / when_ordering.ex
Created June 8, 2021 00:19
Elixir example of when ordering gone wrong
defmodule Greeting do
def say_hello(name) do
"Hello #{name}"
end
def say_hello(name) when name === "Brooklin" do
"Oh it's just you again"
end
end
Greeting.say_hello("Brooklin") # Hello Brooklin
@BrooklinJazz
BrooklinJazz / when.ex
Created June 8, 2021 00:17
Elixir example using when in a function
defmodule Greeting do
def say_hello(name) when name === "Brooklin" do
"Oh it's just you again"
end
def say_hello(name) do
"Hello #{name}"
end
end
Greeting.say_hello("Brooklin") # Oh it's just you again
@BrooklinJazz
BrooklinJazz / default_arguments.ex
Created June 8, 2021 00:12
Default argument example in elixir
defmodule Greeting do
def say_hello(name \\ "Brooklin") do
"Hello #{name}"
end
end
Greeting.say_hello() # Hello Brooklin
@BrooklinJazz
BrooklinJazz / naming_conventions.ex
Created June 8, 2021 00:08
Naming convention example for elixir
defmodule M do
def above_20?(val) do
val > 20
end
end
M.above_20?(21) # true
@BrooklinJazz
BrooklinJazz / string.ex
Last active June 8, 2021 00:02
String Elixir examples
String.length "a string" # 8
String.contains?("string", "str") # true
String.at("mystring", 2) # s
String.slice("mystring", 2, 3)
String.split("my string", " ") # ["my", "string"]
String.reverse("string") # gnirts
String.upcase("string") # STRING
String.downcase("STRING") # string
String.capitalize("string") # "String"
@BrooklinJazz
BrooklinJazz / mapget.ex
Created June 7, 2021 22:23
Map get syntax
# with string syntax
map = %{"key" => "value"}
Map.get(map, "key") # value
# with atom syntax
map = %{key: "value"}
Map.get(map, :key) # value
@BrooklinJazz
BrooklinJazz / tuple.ex
Created June 7, 2021 22:08
Tuple examples in Elixir
Tuple.append({1}, 2) # {1, 2}
Tuple.duplicate(0, 5) # {0, 0, 0, 0, 0}
Tuple.insert_at({1, 3}, 1, 2) # {1, 2, 3}
@BrooklinJazz
BrooklinJazz / map_update.ex
Last active June 7, 2021 22:24
Map update syntax Elixir
map = %{"key" => "value"}
%{map | "key" => "value2"} # %{"key" => "value2"}
%{map | "key2" => "value2"}
# ** (KeyError) key "key2" not found
main.exs:3: (file)
@BrooklinJazz
BrooklinJazz / headtail.ex
Created June 7, 2021 18:50
head and tail example
[head | tail] = [1,2,3]
head # 1
tail # [2, 3]
@BrooklinJazz
BrooklinJazz / list.ex
Last active June 7, 2021 18:48
List module examples
List.last([1,2,3]) # 3
List.first([1, 2, 3]) # 1
List.delete([1,2,3], 1) # [2, 3]
List.delete_at([1,2,3], 0) # [2, 3]