Ruby Enumerable Magic: The Basics


  1. The Basics
  2. Unary Ampersand Operator
  3. Booleans
  4. Filters
  5. New Collections
  6. Aggregates
 

You’re probably familiar with Ruby’s Enumerable module, even if you don’t know it by that name. It adds neat methods to arrays, like map, inject, select, and so on. You might have thought (like I did for a long time) that these methods were *array* methods, but they’re not.

Ruby’s arrays use Enumerable, and you can as well, in any class you want. Of course, the class should represent a collection of things, or all the iterative methods in Enumerable wouldn’t make much sense. Let’s say we have a Team class, that manages a group of members:

class Team
  include Enumerable
  
  attr_accessor :members
  
  def initialize
    @members = []
  end
  
  def each &block
    @members.each{|member| block.call(member)}
  end
end

Enumerable requires that your class contain an each method that serves up the items in the collection. All the other Enumerable methods rely on this. Now we can use the map method, for instance:

irb(main):001:0> require 'team.rb'
=> true
irb(main):002:0> team = Team.new
=> #<Team:0x100391088 @members=[]>
irb(main):003:0> team.members = ['joshua', 'gabriel', 'jacob']
=> ["joshua", "gabriel", "jacob"]
irb(main):004:0> team.map{|member| member.capitalize}
=> ["Joshua", "Gabriel", "Jacob"]

Now we can call any Enumerable methods on our team itself, and it will assume we want to work with the members array within. Enumerable can be a powerful mix-in to your own classes. We can even take this a step further, and clean up our call to map:

team.map(&:capitalize)

If you haven’t seen this before, it’s called the unary ampersand operator, and it’s the subject of my next post.

About these ads

Tags: , , , , , ,

3 Responses to “Ruby Enumerable Magic: The Basics”

  1. mephux Says:

    Hey Jaime

    Man, wish I was back in Kansas for these talks! One convention i like to use is:

    def each_member(&amp;block)
      return enum_for(:each_member) unless block
      @members.each do |member|
        yield member
      end
    end
    
    def members
     each_member.to_a
    end
    
    • Jaime Bellmyer Says:

      Hey Dustin – glad to hear from you! The team example is obviously a little contrived, but it shows how to use Enumerable. I kind of like what you’ve done – given a method that will act on each member so naturally. I still like the unary ampersand though, and I’ll be expanding on how to use it in tomorrow’s post. Take it easy!

  2. Магия модуля Enumerable в Ruby: Основы | Разработка на Ruby и Rails c нуля Says:

    […] статьи на английском: Ruby Enumerable Magic: The Basics Tags: enumerable, Ruby, […]

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


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: