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.
Tags: ampersand, array, block, enumerable, Rails, Ruby, ruby on rails

November 30, 2010 at 10:00 am |
Hey Jaime
Man, wish I was back in Kansas for these talks! One convention i like to use is:
def each_member(&block) return enum_for(:each_member) unless block @members.each do |member| yield member end end def members each_member.to_a endNovember 30, 2010 at 10:27 am |
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!
January 10, 2011 at 3:45 pm |
[...] статьи на английском: Ruby Enumerable Magic: The Basics Tags: enumerable, Ruby, [...]