MC logo

Linked List

^  Ruby Example Code

<<Inclusion Modules list.rb Tree>>

# Here is a linked list class.  Since there's not much point in writing
# such a class when you already have all the Ruby data structures
# available, you might have figured out it's here to demonstrate something:
# including a module.

# A linked list
class List
  # Nodes for the linked list.
  class Node
    # Get the last facility which scans to the end of the list.
    include Follower

    def initialize(d, n = nil)
      @val = d
      @next = n
    attr_reader :next, :val
    attr_writer :next

  # Get the printing facility.
  include Printer

  # Create the list with its first node.
  def initialize(first)
    @head =

  # Add at the front.  We can only add, and the list is created with one
  # node, so no special case for empty list.  How nice.
  def at_front(v)
    n = = @head
    @head = n

  # Add to the end of the list.
  def at_end(v)
    n = = n

  # Process each member of the list.  The yield operator calls the block
  # sent to the function.
  def each
    p = @head
    while p != nil
      yield p.val
      p =
See:Programming Ruby [1][2]Ruby User's Guide

The List class, and Node class inside it, use the include directive to add methods from the Follower and Printer modules, respectively.

Note the implementation of the iterator for List: the yield operation runs the code block provided to the iterator.
<<Inclusion Modules Tree>>