Christopher Dicely
3/4/2008 2:33:00 AM
And, no, I can't explain why I used this:
--
NAMES.each {|name| yield const_get(name.to_s)}
--
Instead of:
---
INSTANCES.each {|season| yield season}
--
Just trying to make things too complex, I guess.
On Mon, Mar 3, 2008 at 6:28 PM, Christopher Dicely <cmdicely@gmail.com> wrote:
> On Mon, Mar 3, 2008 at 3:44 PM, James Britt <james.britt@gmail.com> 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.)
>