From: AW Date: 2002-08-22T04:33:26+09:00 Subject: Re: the power of ruby Great example! Thats a lot to chew on. >My "imaginative" attempt is below. > > >=begin > starfield.rb, by Gavin Sinclair > > This is a verbose, almost obfuscated implementation of a simple > program in Ruby. It is intended to demonstrate the following just > for the sake of it: > - class > - attr_reader > - Comparable mixin > - Range, esp. of user-defined type > - for x in y syntax > - array manipulation >=end > >WIDTH = 78 > >class Star > include Comparable # Import comparison operations <, ==, ... > > attr_reader :n # Attribute ':n' can be read through auto-defined > # method 'n'. > > def initialize(n) # Called when a new Star object is created. > @n = n > end > > def <=>(other) # Compare to another Star. > @n <=> other.n > end > > def succ # Next element in sequence, needed for Range. > Star.new(@n+1) > end > > def to_s # The value that is returned when the object is > " " * @n + "*" # coerced into a String. > end >end > > ># We can create a Range of Stars. >starfield = Star.new(0) .. Star.new(WIDTH) > >loop do > # Print them in turn. > for star in starfield > puts star > end > > # To print them going back, we have to get dirty. Note that we > # ignore the rightmost star, to get the effect you want. > for star in starfield.to_a.reverse[1..-1] > puts star > end >end > >(END OF CODE) > >Cheers, >Gavin > >