This week in the Elixir Cauldron we are going to compare Elixir's anonymous functions to Ruby's lambda expressions. Although we don't think of Ruby as a functional language, there are features of Ruby that resemble its functional cousins, including its use of lambda expressions.

Let's look at examples in both languages. First, define an anonymous function in Elixir and then look at the Ruby equivalent.

iex(1)>say=fn()->IO.puts"Hello"endiex(2)>say.()Hello:ok

Here is the same functionality replicated in Ruby:

irb(main):001:0>say=->{puts"Hello"}irb(main):002:0>say.()Hello=>nil

Those were oversimplified examples, but they do illustrate the syntactical similarities in the two languages. The similarities don't stop there.

Like other functional languages, Elixir functions are first class citizens. What does that mean? It means that functions not only yield values but they can also be assigned to variables, passed as arguments, or returned from other functions. We've seen functions assigned to variables, so how does passing as an argument or returning a function compare?

To see this in action, we will define a function that accepts a function as an argument and executes it:

defmoduleSimpledodefcall(func)dofunc.()endend

Now in iex call the function, passing an anonymous function as an argument:

iex(1)>Simple.callfn()->IO.puts"Hello"endHello:ok

How would that be implemented in Ruby and irb?

classSimpledefself.call(func)func.()endend

irb(main):001:0>Simple.call->{puts"Hello"}Hello=>nil

What about returning a function from another function?

defmoduleSimpledodefreturndofn()->IO.puts"Hello"endendend

Now call the function from iex:

iex(1)>say=Simple.returniex(2)>say.()Hello:ok

And again in Ruby and irb:

classSimpledefself.return->{puts"Hello"}endend

irb(main):001:0>say=Simple.returnirb(main):002:0>say.()Hello=>nil

These are simple examples but their purpose is to illustrate the similarities between the two languages. Uncovering syntactical similarities can ease a transition between languages.

Next week, we will expand our view of Elixir functions by addressing a feature Ruby doesn't include, pattern matching.