Lambdas in Ruby

How remove redundancy in your code?

I had situation where I worked with many different (but in some way similar) collections in Ruby. This collections had very similar methods to search elements by name. In this particular example I decided to use lambda. Let me show you how this looks like.

Code which I get looks like this:

@first_collection.select do |activity|
  activity.name == 'name'
end

This is not bad code but in others places I had similar things. Collections (I mean arrays) and names were only changes. Like this:

@second_collection.select do |activity|
  activity.name == 'name1' || activity.name == 'name2'
end

So I decided to use lambda. I created method which generate lambda for different collections. As an arguments lambda get names of activities to select. Method looks like this:

def prepare(collection)
  lambda do |*names|
    collection.select { |activity| names.include?(activity.name) }
  end
end

When you prepare collection, you can start looking for activities with specific names.

@collection = prepare(collection)

@collection.call('name')
@collection.call('name1', 'name2')

This solution reduce number of the same structure in our code. There is one place where collection is declared. To be honest with you this was only temporary change because at the end of my refactoring collection became separate object. But for this moment in time solution was very clear and simple.

If you like to know more about lambda and functional programming, you can read my presentation available here.

I hope that was interesting for you. Live a comment and see you next time. Bye!