From: Christopher Dicely Date: 2008-03-04T11:27:57+09:00 Subject: Re: Question on the Ruby Programming Language Book On Mon, Mar 3, 2008 at 3:44 PM, James Britt wrote: > Bharat Ruparel wrote: > > > 1 Why do you have to create enumerated objects this way? This seems a > > long way off from Ruby's philosophy of being succint. Just to define a > > few "object" constants I have to go through this? > > > > Well, you can add this method: > > > def next > INSTANCES[ (@n+1) % 4] > end > > > and then do this: > > > season = Season::Autumn > puts season > puts season.next > puts season.next.next > Or, better (in Ruby 1.9) add this instead: --- class Season extend Enumerable def self.each NAMES.each {|name| yield const_get(name.to_s)} self end # more direct than making it sortable by defining a <=> operator, # though you could do that instead. def self.sort(&block) if block then to_a.sort(&block) else to_a end end end --- And then try (not really all that useful for seasons, but shows that you've got the full power of Enumerable at hand): --- Season.sort {|s1, s2| s1.to_s <=> s2.to_s}.each {|s| puts s.to_s} Season.sort_by {|season| season.to_s}.each {|s| puts s.to_s} Season.map {|season| season.to_s}.each {|s| puts s} --- And finally (the one I like the most): --- seasons = Season.cycle puts seasons.next puts seasons.next puts seasons.next . . . --- (You can do the same thing to make the class Season an Enumerable in Ruby 1.8, but Ruby 1.9's Enumerators and the Enumerable#cycle method really make this cool, IMO.)