TomHale
Why assign if/else to a variable?
In Elixir Succinctly I read:
Since everything in Elixir is an expression, and if is no exception, the if…else construct returns a value that we can assign to a variable for later use:
a = if test_conditional do # ...
What are some practical usages of this?
Most Liked
NobbZ
You can have the value of a variable depending on some condition.
In other languages you see code like the following which would not work in Elixir due to elixirs scoping rules:
a = 2
if condition then:
a = 1
pavancse17
if suppose you want to change any variable value inside if block in Elixir. You need to get back and re-assign the value to the same variable.
This is the code you will expect to work. But it won’t.
iex(7)> a = 5
5
iex(8)> is_odd = nil
nil
iex(9)> if rem(a, 2) == 0 do
...(9)> is_odd = false
...(9)> else
...(9)> is_odd = true
...(9)> end
warning: variable "is_odd" is unused (if the variable is not meant to be used, prefix it with an underscore)
iex:12
warning: variable "is_odd" is unused (if the variable is not meant to be used, prefix it with an underscore)
iex:10
true
iex(10)> is_odd
nil
So you need to re-assign it back like below:
iex(13)> a = 5
5
iex(14)>
nil
iex(15)> is_odd = if rem(a, 2) == 0 do
...(15)> false
...(15)> else
...(15)> true
...(15)> end
true
iex(16)> is_odd
true
iex(17)>
NobbZ
There was a warning about the “imperative assignment” from 1.2 or 1.3 on, and it actually worked until 1.8 or 1.9…
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








