#!/usr/bin/ruby class Walker Speed = 10 # class constant @@width = 60 # class variable @char = 'W' # class instance variable def Walker.char #class method return @char end def Walker.setWidth newWidth # class method with parameter @@width = newWidth end def char #public instance method self.class.char # access class method from instance end def initialize # initialize is always private @counter = @@width / 2 # instance variable end def walk computeDirection updateCounter basicWalk end def run printf " " * 4; puts "-" * @@width (1..Speed).each { |line| printf "%2i: ", line; walk } end def getCounter return @counter end protected # accessable within instances of class and subclasses def left return -1 end def right return 1 end def forward return 0 end def computeDirection @direction = forward end def basicWalk output = (0..@counter-1).collect{ char } puts "#{output}" end private # accessable within instances of class def updateCounter @counter += @direction * Speed / 10 @counter = @@width if @counter > @@width @counter = 1 if @counter < 1 end end class RandomWalker < Walker # subclass @char = 'R' def computeDirection @direction = rand < 0.5 ? left : right end end # example if $0 == __FILE__ Walker.new.run randomWalker = RandomWalker.new randomWalker.run Walker.setWidth 20 Walker.new.run RandomWalker.new.run randomWalker.run end