From: Aryeh Friedman Date: 2003-07-06T03:47:51+09:00 Subject: Re: Re (repost): Is this a bug? gabriele renzi wrote: This is what I get for posting "simplified" code in the real code there is no component that is an array or could be interpreded as one here is the real code. Note: the bug specifically is why does ModTree::TreeNode::find require all four args it seems that it should only require aVal same for Tree::Dump. A related question is there an easier way to impliment Tree::insert* TreeNode::find*. It seems the C++ notion of overloaded functions would be the ideal way. #!/usr/bin/env ruby # # Platform: unspecified # Author: Aryeh M. Friedman # Version of orgin: mudng.0.0.0.1 # # Copyright (c) 2003. Aryeh M. Friedman and the MudNG Project. All rights reserved. # Library for adding generic trees (NOT Hash/Path Trees!!!) to ruby module ModTree class TreeException < RuntimeError end class TreeNode attr :nid attr :parent attr :level attr :val @@tid=0 def initialize(aVal,aParent=nil) @nid=@@tid @@tid+=1 @val=aVal @parent=aParent if @parent!=nil @parent.addChild(self) @level=@parent.level+1 else @level=0 end @branchs=[] @cur_branch=0 end def addChild(aTreeNode) @branchs.push(aTreeNode) end def reset @cur_branch=0 end def find(aVal) walk do |bVal, bLevel, bPid, bId| aVal==bVal end end def findById(aId) walk do |aVal,aLevel,aParentId,aNodeId| aId.to_i==aNodeId.to_i end end def getNext if @cur_branch>@branchs.length-1 reset if @parent!=nil return @parent.getNext else return nil end end @cur_branch+=1 return @branchs[@cur_branch-1] end def walk if self.parent!=nil raise TreeException,"Not root node" end node=self while node!=nil if node.parent == nil pid=0 else pid=node.parent.nid end if yield(node.val, node.level, pid, node.nid)==true tmp=node while tmp!=nil tmp.reset tmp=tmp.parent end node.reset return node end node=node.getNext end end end class Tree def initialize @root=TreeNode.new(nil) end def walk(&block) @root.walk(&block) end def find(aVal) @root.find(aVal) end def insert(aParent,aVal) node=@root.find(aParent) TreeNode.new(aVal,node) end def insertById(aId,aVal) node=@root.findById(aId) TreeNode.new(aVal,node) end def getParent(aVal) node=@root.find(aVal) if node!=nil then return node.parent else return nil end end def dump @root.walk {|aVal, aLevel, aParentId, aId| puts "#{' '.rjust(aLevel)}#{aVal}"} end end end > supposing it was: > foo.each { |aFoo| > aFoo.ack{|aVal| puts aVal } > } > > it is the correct behaviour, try this: > > foo.each { |aFoo| > aFoo.ack{|aVal| puts aVal.class } > } > > foo.each { |aFoo| > aFoo.ack{|aVal,otherVal| puts aVal } > } > > > output: > Array > Array > Array > ack > bar > foo > > > Ruby splits the list for you, but if you give just one arg to the > proc, that arg is an Array