From: Robert Klemme Date: 2009-10-14T16:47:50+09:00 Subject: Re: Enumerating and mixin. 2009/10/14 Rajinder Yadav : > 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? Exactly - as Brian wrote. You can "see" this at work here: 09:45:55 ~$ ruby19 -e 'class X;include Comparable;def <=>(o);0 end;end;x=X.new;set_trace_func lambda {|*a| p a};x, Kernel] ["line", "-e", 1, nil, #, nil] ["c-call", "-e", 1, :<, #, Comparable] ["call", "-e", 1, :<=>, #, X] ["line", "-e", 1, :<=>, #, X] ["return", "-e", 1, :<=>, #, X] ["c-return", "-e", 1, :<, #, Comparable] 09:46:07 ~$ >> 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?"] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/