From: "A. S. Bradbury" Date: 2006-09-08T22:26:20+09:00 Subject: Puzzling bug with yielded array I have a Node class, children are stored in a hash with the node's name as the key and the child node object as the value. I have the method Node#each_level that yields each level of the node tree as an array: def each_level(include_self=false) if include_self node_queue=[self] else node_queue=self.children.values end yield node_queue while node_queue.any? {|node| node.children.empty? == false} do node_queue.collect! {|node| node.children.values} node_queue.flatten! yield node_queue end end Here is the code that demonstrates the problem: require 'ariel' root=Ariel::Node.new :root child1=Ariel::Node.new :child1 child2=Ariel::Node.new :child2 child1_1=Ariel::Node.new :child1_1 root.add_child child1 root.add_child child2 child1.add_child child1_1 results=[] puts "Results when making an array then flattening it" root.each_level do |level| puts "Yielded #{level.inspect}" puts raise StandardError unless level.kind_of? Array results << [level].flatten # works end puts "results=#{results.inspect}" puts results=[] puts "Results when just adding the array" root.each_level do |level| puts "Yielded #{level.inspect}" puts raise StandardError unless level.kind_of? Array raise StandardError if level.any? {|val| val.kind_of? Array} results << level # doesn't work end puts "results=#{results.inspect}" I'm really, really stumped. Here's the output: > Results when making an array then flattening it > Yielded [Ariel::Node - node_name=:child1; parent=:root; > children=[:child1_1];, Ariel::Node - node_name=:child2; parent=:root; > children=[];] > > Yielded [Ariel::Node - node_name=:child1_1; parent=:child1; children=[];] > > results=[[Ariel::Node - node_name=:child1; parent=:root; > children=[:child1_1];, Ariel::Node - node_name=:child2; parent=:root; > children=[];], [Ariel::Node - node_name=:child1_1; parent=:child1; > children=[];]] > > Results when just adding the array > Yielded [Ariel::Node - node_name=:child1; parent=:root; > children=[:child1_1];, Ariel::Node - node_name=:child2; parent=:root; > children=[];] > > Yielded [Ariel::Node - node_name=:child1_1; parent=:child1; children=[];] > > results=[[Ariel::Node - node_name=:child1_1; parent=:child1; > children=[];], [Ariel::Node - node_name=:child1_1; parent=:child1; > children=[];]] The yielded data is always correct and the same each time, but as you can see the second results array is wrong. Can anyone explain what's going on here? Alex