sample/list.rb


DEFINITIONS

This source file includes following functions.


   1  # Linked list example
   2  class MyElem
   3    # object initializer called from Class#new
   4    def initialize(item)
   5      # @variables are instance variable, no declaration needed
   6      @data = item
   7      @succ = nil
   8    end
   9  
  10    def data
  11      @data
  12    end
  13  
  14    def succ
  15      @succ
  16    end
  17  
  18    # the method invoked by ``obj.data = val''
  19    def succ=(new)
  20      @succ = new
  21    end
  22  end
  23  
  24  class MyList
  25    def add_to_list(obj)
  26      elt = MyElem.new(obj)
  27      if @head
  28        @tail.succ = elt
  29      else
  30        @head = elt
  31      end
  32      @tail = elt
  33    end
  34  
  35    def each
  36      elt = @head
  37      while elt
  38        yield elt
  39        elt = elt.succ
  40      end
  41    end
  42  
  43    # the method to convert object into string.
  44    # redefining this will affect print.
  45    def to_s
  46      str = "<MyList:\n";
  47      for elt in self
  48        # short form of ``str = str + elt.data.to_s + "\n"''
  49        str += elt.data.to_s + "\n"
  50      end
  51      str += ">"
  52      str
  53    end
  54  end
  55  
  56  class Point
  57    def initialize(x, y)
  58      @x = x; @y = y
  59      self
  60    end
  61  
  62    def to_s
  63      sprintf("%d@%d", @x, @y)
  64    end
  65  end
  66  
  67  # global variable name starts with `$'.
  68  $list1 = MyList.new
  69  $list1.add_to_list(10)
  70  $list1.add_to_list(20)
  71  $list1.add_to_list(Point.new(2, 3))
  72  $list1.add_to_list(Point.new(4, 5))
  73  $list2 = MyList.new
  74  $list2.add_to_list(20)
  75  $list2.add_to_list(Point.new(4, 5))
  76  $list2.add_to_list($list1)
  77  
  78  # parenthesises around method arguments can be ommitted unless ambiguous.
  79  print "list1:\n", $list1, "\n"
  80  print "list2:\n", $list2, "\n"