Ruby Method to Block (Lambda)

In Ruby on Rails development, I have been known to use symbol to proc. Recently, I needed to re-use a method as a block.

Here’s a contrived example of what I was doing:

Group.all.sort {|a,b| a.name <=> b.name}

However, I wanted to re-use this sort and ended-up refactoring it to:

def group_sort(a, b)
  a.name <=> b.name
end
Group.all.sort {|a,b| group_sort(a, b)}

Although this allowed me to re-use my sorting mechanism just fine, it seemed verbose. I was able to be succinct by using a lambda like so:

group_sort = lambda{|a,b| a.name <=> b.name}
Group.all.sort &group_sort

(Using a lambda may be obvious to Ruby pros, but I’m not there yet.)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s