Don't you hate when and elsif??

Everyone needs change. I code in ruby most of the day, so I like to code in Scala just for the kicks.

One of the features I miss in Ruby after coding in scala is Pattern Matching.

Wouldn't it be nice to be able to do something like that in ruby instead of using ugly if's and whens?

Do you like this code?

class Dummy
    def initialize(x, y, z)
            @x, @y, @z = 1, 2, 3
    end

    def sum
            @x + @y + @z
    end
end

obj = Dummy.new(1, 2, 3)

# Later on... after the sun sets and the moon rises

if obj.responds_to?(:x) && obj.responds_to?(:y)
    puts "Do something awesome with dummy.x and dummy.y"
else if obj.kind_of?(Dummy)
    puts "This is a dummy"
end

Well, maybe it's ok, but it can get messy.

So I wrote a small ruby gem to be able to match objects against patterns. So the above example could be written as:

Matchmaker.match(obj) do
    pattern :x, :y do puts "Do something awesome with #{x} and #{y}" end
    pattern Dummy do puts "This is a dummy" end
end

Looks good hum?

It's even better when you are trying to match enums over a set of conditions:

array_obj = [1, 2, 3, 4]

if array_obj.size == 1
    puts "The single element is array_obj[0]"
elsif array_obj.size == 2
    first, second = array_obj.first(2)
    puts "first: #{first}, second: #{second}"
else
    first_element, others = array_obj.first, array_obj[1, array_obj.size]
    puts "head is #{first_element}, tail is #{others}"
end

This can be written with Matchmaker like this:

Matchmaker.match(array_obj) do
    enum :x do puts "The single element is array_obj[0]" end
    enum :x, :y do puts "first: #{x}, second: #{y} end"
    enum_cons :x, :xs do puts "head is #{x}, tail is #{xs}" end
end

I think it's neat :)

There are more example at the Github Repo.



comments powered by Disqus