F
Fearless Fool
I've not quite wrapped my head around Enumerations, but I suspect I'm
just being dense. Assume the following small code fragment:
-----
TNode = Struct.newleft, :right, :value)
class TNode
def traverse(&block)
left.traverse(&block) if left
right.traverse(&block) if right
yield(self)
end
end
-----
... which lets me define a method such as:
-----
def find_node(value)
traverse { |node| return node if (node.value == value) } || nil
end
-----
For somewhat didactic reasons, I'd prefer a method TNode#traversal(),
that returns an Enumerable, so I could do something like:
-----
def find_node(value)
traversal.find {|n| n.value == value}
end
-----
... but as I mentioned, I haven't figured out the right way to structure
this. Any hints? Or is it not worth the effort?
TIA.
- ff
just being dense. Assume the following small code fragment:
-----
TNode = Struct.newleft, :right, :value)
class TNode
def traverse(&block)
left.traverse(&block) if left
right.traverse(&block) if right
yield(self)
end
end
-----
... which lets me define a method such as:
-----
def find_node(value)
traverse { |node| return node if (node.value == value) } || nil
end
-----
For somewhat didactic reasons, I'd prefer a method TNode#traversal(),
that returns an Enumerable, so I could do something like:
-----
def find_node(value)
traversal.find {|n| n.value == value}
end
-----
... but as I mentioned, I haven't figured out the right way to structure
this. Any hints? Or is it not worth the effort?
TIA.
- ff