From: Rajinder Yadav Date: 2009-10-13T08:47:58+09:00 Subject: Re: Enumerating and mixin. Rajinder Yadav wrote: > I am trying to learn the correct way to enumerate in Ruby, a few things > are missing in my 1st stab at this. How do I use mixin with Enumerable > to rewrite the class I have below? I can't seem to find a concrete > example online? > > I know I am also missing code to override <=> if I wanted to do sorting, > are the other overrides I am missing? > > How do I make my code more elegant, Thanks! > > > class Vowels > def initialize > @index = 0 > @list = %w(a e i o u) > end > > def each > while( @index < @list.size ) > if @index >= @list.size > yield nil > exit > else > yield @list[@index] > @index += 1 > end > end > end > > def first > @index=0 > end > end > > obj = Vowels.new > > obj.each { |x| puts x } > > > OK I managed to sweet the code down to the following, is there anything else I missed? class Vowels include Enumerable def initialize @list = %w(u e a o i) end def each @list.each { |item| yield item } end end obj = Vowels.new obj.each { |s| print s } puts "" obj.sort.each { |s| print s } puts "" -- Kind Regards, Rajinder Yadav http://DevMentor.org Do Good ~ Share Freely