From: Robert Klemme Date: 2005-04-13T15:04:37+09:00 Subject: Re: help traversing and modifying hash key and value inplace "Trans" schrieb im Newsbeitrag news:1113350541.397689.163850@l41g2000cwc.googlegroups.com... > So here's what I've settled on. Good? Or is there still a better way to > do? > > # Returns a new hash created by traversing the hash and its subhashes, > # executing the given block on the key and value. The block should > # return a 2-element array of the form +[key, value]+. > # > # h = { "A"=>"A", "B"=>"B" } > # h.traverse { |k,v| [k.downcase, v] } > # h #=> { "a"=>"A", "b"=>"B" } > # > def traverse(&b) > inject({}) do |h,(k,v)| > nk, nv = b[k,v] > h[nk] = (Hash === nv ? nv.traverse(&b) : nv) > h > end > end There's a subtle thing: you decide whether you traverse on the other instance *after* the block got it. Dunno whether that is what you want but I think I remember the other version decided this based on the original value. You probably want to leave that out altogether and have the block decide this. In this case traverse would become even simpler. Ah, and traverse will crash for recursive structures. >> h={} => {} >> h[1]=h => {1=>{...}} >> h.traverse {|*a| a} SystemStackError: stack level too deep from (irb):5:in `traverse' from (irb):3:in `inject' from (irb):3:in `each' from (irb):3:in `inject' from (irb):3:in `traverse' from (irb):5:in `traverse' from (irb):3:in `inject' from (irb):3:in `each' from (irb):3:in `inject' from (irb):3:in `traverse' from (irb):5:in `traverse' from (irb):3:in `inject' from (irb):3:in `each' from (irb):3:in `inject' from (irb):3:in `traverse' from (irb):5:in `traverse' .... 11844 levels... from (irb):5:in `traverse' from (irb):3:in `inject' from (irb):3:in `each' from (irb):3:in `inject' from (irb):3:in `traverse' from (irb):5:in `traverse' from (irb):3:in `inject' from (irb):3:in `each' from (irb):3:in `inject' from (irb):3:in `traverse' from (irb):5:in `traverse' from (irb):3:in `inject' from (irb):3:in `each' from (irb):3:in `inject' from (irb):3:in `traverse' from (irb):12>> :-) Kind regards robert