Ruby on Rails – Easier enumerations (Select, Collect, Map) using Ampersand

a = [] # setup array
0.upto(100) do #just make up some array
a << rand(1000)
end
s = a.in_groups_of(6,false) # make it an array of arrays (so we can use the sort method on each element of the outer array)
s.collect(&:sort) #sort each array inside the outer array in one easy step

What are we looking at? the ‘&:’ is the special bit.  It replaces the more cumbersome

s.collect{|i| i.sort}

Posted on March 31, 2009 at 10:31 am by Jordan Carter · Permalink
In: Uncategorized · Tagged with: , , , ,

One Response

  1. Written by Stephan
    on March 31, 2009 at 5:45 pm
    Permalink

    Yes that’s nice. It’s also available in the “extensions” gem – for those running plain Ruby 1.8.6.
    And there’s also http://github.com/mynyml/every/ which gives you an even nicer syntax. And mynyml’s “every” also take arguments. One exampl from mynyml:

    %w( axb dxf ).every.gsub(/x/,’y’) #=> [‘ayb’, ‘dyf’]

    Nice, ist’n it.

Leave a Reply