This is a example on pattern matching.
Given the Map/Hash input:
input = %{name: "Alice Foo", points: 100, email: "alicefoo@myemail.com"}
The goal is to determine the user rank, by its points:
0..50
-> Starter50..200
-> Member>200
-> Veteran
The code in Elixir using pattern matching:
defmodule Rank do
@moduledoc """
Offers means to perform user ranking computations.
"""
@typedoc """
A user rank.
"""
@type rank :: :starter | :member | :veteran
@doc """
Finds the rank of a given user.
"""
@spec find(%{points: integer()}) :: rank()
def find(%{points: n}) when n <= 50, do: :starter
def find(%{points: n}) when n <= 200, do: :member
def find(_user), do: :veteran
end
Here's how you use it:
iex(1)> Rank.find(input)
:member
The same code in Ruby:
class Rank
# Offer means to perform ranking computations.
# Finds the rank of a given user.
def self.find(user)
case user[:points]
when 0..50
:starter
when 50..200
:member
else
:veteran
end
end
end
And running it:
irb(main):001:0> Rank.find(input)
=> :member
Patter matching makes the code more elegant, expressive and easier to read.
@oliverswitzer
What you did is great, and its the more "functional" approach to the solution in Ruby. You're using Ruby's so called "guard clauses", which is one of the fundamental functional building blocks. Your code in Ruby follows what I understand by functional as it's not only using guard clauses, but is also defining a class method, which is one of the ways to approach namespaced functions without keeping state, like classes and objects.
Though I must admit the examples I came up with are weak, this is a hard subject to discuss about. In this snippet here I was only trying to show the advantage of pattern matching. But keeping any code functional-like (as you did) is a advantage too, so I think it should be preferred for "high level" systems.