Making Code Blocks With & (Ampersand)

Enumerable objects, such as arrays, have iterator methods which take a code block as an argument. Here's an example as it may appear in a Rails project:

@users = User.find(:all)
usernames = @users.collect {|user| user.login}

Here, the collect method returns an array with the results of running the code block once for every user object in the @users array. The code block executes the “login” attr_reader method, so all logins are collected in an array called usernames.

In Rails, there is a shortcut for this, which makes use of the ampersand:

@users = User.find(:all)
usernames = @users.collect &:login

This code calls the login attr_reader method for each element in @users. Here, the ampersand (&) is syntactic sugar for a to_proc call on the Symbol object. This to_proc method converts the symbol into a method call. The to_proc method in Rails looks something like this:

class Symbol

    # A generalized conversion of a method name
    # to a proc that runs this method.
    #
    def to_proc
        lambda {|x, *args| x.send(self, *args)}
    end

end

Credits: Eli Bendersky's Website.


Personal Tools