Thursday, June 28, 2007

tree class of Ruby


class Tree
include Enumerable

attr_accessor :left, :right

def initialize(str)
@str = str
end

def each
left.each {|t| yield t } if left
right.each{|t| yield t } if right
yield @str
end

end

t1 = Tree.new('a')
t1.left = Tree.new('a_left')
t1.right = Tree.new('a_right')
t1.left.left = Tree.new('a_left_left')
t1.right.left = Tree.new('a_right_left')
t1.right.right = Tree.new('a_right_right')

t1.each {|t| puts t}

# >> a_left_left
# >> a_left
# >> a_right_left
# >> a_right_right
# >> a_right
# >> a

Ruby's module mixin

# All you have to do is write an iterator called each, which returns the elements of our collection in turn. Mix in Enumerable, and suddenly your class supports things such as map, include?, and find_all?. If the objects in your collection implement meaningful ordering semantics using the <=> method, you’ll also get methods such as min, max, and sort.


class A
include Comparable
include Enumerable
attr :n

def initialize(n)
@n = n
end

def each
(1..@n).each do |i|
yield i
end
end

def <=>(b)
self.n <=> b.n
end
end

a = A.new(3)
b = A.new(4)

m = a.map {|i| i.to_s + __LINE__.to_s}

p m

n = a > b

p n

Ruby Catch Throw Test


catch :label do
(1..10).each do |i|
(11..13).each do |j|
puts 'i=' + i.to_s + ', j=' + j.to_s
throw :label if i == 3 and j == 12
end
end
end

puts 'over'