What is "def" and why it has to come with "do"

First of all, I want to say sorry because it’s probably a really dumb question…

I’m starting to learn Elixir and i come from a different background (Typescript) so i’m having some difficulty understanding the syntax of modules and methods.

With that being said, what does def mean when declaring a method? And why it has to come with do in the end?

Hello, there are no methods in Elixir. The organization is “functions” inside “modules”. “def” is for “define” a function. And “do” is for “open” a code block, like “{ }” in TypeScript.

2 Likes

The syntax is inspired by ruby. You can compare def to public function … you see in many OO languages (not in js/ts though), while do … end are like { … }.

2 Likes

def means “define the funtion with name, arguments and body”.

The do is necessary to distinguish body from name and args.

In other languages curly braces are used or indentation.

Also in Elixir there are no methods, only functions.

3 Likes

… and to add to the previous replies, do end is a syntaxic sugar for , do:

You can write

if ... do
  ...
else
  ...
end

# as
if ..., do: ..., else: ...

:slight_smile:

3 Likes

Thanks for the answer!!

The elixir course that I’m doing has a class called “Elixir modules and methods”, so I’m a little confused right now haha.

What are the things that Elixir has that is inspired by Ruby? I’m curious now haha

It surely is because the teacher comes from oop, but talking about methods is strictly prohibited here :slight_smile:

1 Like

Oh, i see. Is it because Elixir is a functional language, right?

The class is “The Complete Elixir and Phoenix Bootcamp”? :smiley:

The Elixir creator answered something similar in another post. But yes! Is a little bit confusing :laughing:

The BEAM uses MFA: Module, Function, Argument

If you look at ruby code and elixir code they look very similar. There are a lot of similar keywords and other syntactical elements used. That’s about it though. It does not mean elixir works similar than ruby, to the contrary.

The creator of Elixir, @josevalim is a former Ruby Core Member. But if You look at Erlang, the syntax is inspired by Prolog.

Elixir is way closer to Erlang than to Ruby. Erlang looks like this…

sort([Pivot|T]) ->
    sort([ X || X <- T, X < Pivot]) ++
    [Pivot] ++
    sort([ X || X <- T, X >= Pivot]);
sort([]) -> [].