Last active
December 11, 2015 20:29
-
-
Save jwhiteman/d5507dbba58b6d5022b0 to your computer and use it in GitHub Desktop.
Elixir vs Ruby (pattern matching vs conditional logic)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# elixir | |
defmodule Example do | |
def work(_msg) do | |
IO.puts "called 1st function" | |
end | |
def work(_msg, data=[_a, _b, _c]) do | |
IO.puts "called 2nd function #{inspect data}" | |
end | |
def work(_msg, data=[a, b, _c, _d]) when is_integer(a) and is_list(b) and a > 5 do | |
IO.puts "called 3rd function #{inspect data}" | |
end | |
def work(_msg, data=[_a, _b, _c, _d]) do | |
IO.puts "called 4th function #{inspect data}" | |
end | |
end | |
Example.work("ok") # calls first function | |
Example.work("ok", [:a, :b, :c]) # calls second function | |
Example.work("ok", [6, [:i_am_a_list], 11, 12]) # calls third function. 'a' is an integer greater than six, 'b' is a list. | |
Example.work("ok", [:a, 42, 99, "hello, world"]) # calls fourth function. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# to get the same output from the same data in Ruby | |
class Example | |
attr_reader :msg, :data | |
def initialize(msg, data = nil) | |
@msg = msg | |
@data = data | |
end | |
def work | |
if data | |
if data.length == 3 | |
puts "called 2nd function #{data}" | |
elsif data[0].kind_of?(Integer) && data[0] > 5 && data[1].kind_of?(Array) | |
puts "called 3rd function #{data}" | |
else | |
puts "called 4th function #{data}" | |
end | |
else | |
puts "called first function" | |
end | |
end | |
end | |
Example.new("ok").work | |
Example.new("ok", [:a, :b, :c]).work | |
Example.new("ok", [6, [:i_am_a_list], 11, 12]).work | |
Example.new("ok", [:a, 42, 99, "hello, world"]).work |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment