From: Rajinder Yadav Date: 2009-10-14T10:40:45+09:00 Subject: Re: Enumerating and mixin. Brian Candler wrote: > Rajinder Yadav wrote: >> OK I managed to sweet the code down to the following, is there anything >> else I >> missed? > > That's fine. So far your Vowels class doesn't really do anything more > than a simple Array would, but you've shown how your class gains methods > from the Enumerable module, and you can now add extra functionality > which is specific to a set of vowels. (This is composition by > delegation, an approach I highly recommend) > > You mention <=>. This isn't needed here because each of the elements you > yield is a String, and strings already have <=> and so the elements can > be sorted. But if you want a different exercise, try: Brian thanks for the demonstration of how to use Comparable, and also pointing out the other methods that can be redefined. If you didn't mention that, I would have stopped at <=>. Although I suspect the other methods make use of <=> internally? > class Vowel > include Comparable > def initialize(v) > @v = v > end > def to_s > @v > end > def <=>(other) > @v <=> other.to_s > end > end > > v1 = Vowel.new("a") > v2 = Vowel.new("e") > v1 < v2 #=> true > v3 = Vowel.new("e") > v2 == v3 #=> true > > Here you're exercising a different mixin, Comparable. It takes any class > which implements a <=> operator, and adds these methods for you: > >>> Comparable.instance_methods > => ["==", ">=", "<", "<=", ">", "between?"] > > Regards, > > Brian. -- Kind Regards, Rajinder Yadav http://DevMentor.org Do Good ~ Share Freely