1998-01-16 07:13:05 -05:00
|
|
|
# Linked list example
|
|
|
|
class MyElem
|
1999-08-13 01:45:20 -04:00
|
|
|
# object initializer called from Class#new
|
1998-01-16 07:13:05 -05:00
|
|
|
def initialize(item)
|
1999-08-13 01:45:20 -04:00
|
|
|
# @variables are instance variable, no declaration needed
|
1998-01-16 07:13:05 -05:00
|
|
|
@data = item
|
|
|
|
@succ = nil
|
2011-03-06 07:51:17 -05:00
|
|
|
@head = nil
|
1998-01-16 07:13:05 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def data
|
|
|
|
@data
|
|
|
|
end
|
|
|
|
|
|
|
|
def succ
|
|
|
|
@succ
|
|
|
|
end
|
|
|
|
|
1999-08-13 01:45:20 -04:00
|
|
|
# the method invoked by ``obj.data = val''
|
1998-01-16 07:13:05 -05:00
|
|
|
def succ=(new)
|
|
|
|
@succ = new
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class MyList
|
|
|
|
def add_to_list(obj)
|
|
|
|
elt = MyElem.new(obj)
|
|
|
|
if @head
|
|
|
|
@tail.succ = elt
|
|
|
|
else
|
|
|
|
@head = elt
|
|
|
|
end
|
|
|
|
@tail = elt
|
|
|
|
end
|
|
|
|
|
|
|
|
def each
|
|
|
|
elt = @head
|
|
|
|
while elt
|
|
|
|
yield elt
|
|
|
|
elt = elt.succ
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
1999-08-13 01:45:20 -04:00
|
|
|
# the method to convert object into string.
|
|
|
|
# redefining this will affect print.
|
1998-01-16 07:13:05 -05:00
|
|
|
def to_s
|
|
|
|
str = "<MyList:\n";
|
|
|
|
for elt in self
|
1999-08-13 01:45:20 -04:00
|
|
|
# short form of ``str = str + elt.data.to_s + "\n"''
|
1998-01-16 07:13:05 -05:00
|
|
|
str += elt.data.to_s + "\n"
|
|
|
|
end
|
|
|
|
str += ">"
|
|
|
|
str
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class Point
|
|
|
|
def initialize(x, y)
|
|
|
|
@x = x; @y = y
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_s
|
|
|
|
sprintf("%d@%d", @x, @y)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
1999-08-13 01:45:20 -04:00
|
|
|
# global variable name starts with `$'.
|
1998-01-16 07:13:05 -05:00
|
|
|
$list1 = MyList.new
|
|
|
|
$list1.add_to_list(10)
|
|
|
|
$list1.add_to_list(20)
|
|
|
|
$list1.add_to_list(Point.new(2, 3))
|
|
|
|
$list1.add_to_list(Point.new(4, 5))
|
|
|
|
$list2 = MyList.new
|
|
|
|
$list2.add_to_list(20)
|
|
|
|
$list2.add_to_list(Point.new(4, 5))
|
|
|
|
$list2.add_to_list($list1)
|
|
|
|
|
2015-06-12 05:20:44 -04:00
|
|
|
# parenthesises around method arguments can be omitted unless ambiguous.
|
1998-01-16 07:13:05 -05:00
|
|
|
print "list1:\n", $list1, "\n"
|
|
|
|
print "list2:\n", $list2, "\n"
|