Hi everyone, I am new to Elixir. I have a function and in this function:
if type == "followers" do
users = ....
else
users = ....
end
if options != nil do
users = ....
end
How can I do this and make sure that the users in the first if/else block will be used in the next if block?
Instead of assigning users
in the if clause you assign "the result"t of the if clause to the variable.
def yourfun() do
users = if type == "followers" do
....
else
....
end
if options != nil do
....
else
users
end
end
3 Likes
Just to add to previous post…
If You don’t do this, You will have a scoping problem, and users disappear after the end of the block
And if you want to avoid if else
clauses this can be written using more functions.
def yourfun(users, type, options) do
users
|> filter_users(type)
|> transform_users(options)
end
def filter_users(users, "followers"), do: ....
def filter_users(users, "other"), do: ....
def filter_users(users, _), do: ....
def transform_users(users, nil), do: users
def transform_users(users, opts), do: ....
4 Likes
thanks so much @cmkarlsson, you solution help me. I am a former Ruby on Rails developer but now switch to Elixir. It still new to me but it is great in many way
No worries. It takes some practice to get used to a more functional way of thinking. something I think we all encountered when we transitioned from traditional procedural/OOP to functional languages.
If your code starts having lots of if/else clauses or other conditionals they can generally be refactored in a more functional way. Remember that in elixir everything is an expression.
1 Like