From: Glenn Ritz on 24 Feb 2010 16:40 Hi, I'd like to be able to take a hash whose values are either hashes or some other object. If the values are hashes, I'd like to iterate over them and keep this up until the values aren't hashes. And I won't know how many level there will be until the program is running. Any suggestions? Thanks, Glenn -- Posted via http://www.ruby-forum.com/.
From: Jonathan Nielsen on 24 Feb 2010 16:52 > > def iteration obj > Â if obj.is_a? Hash > Â Â obj.each { |new_obj| iteration(new_obj) } > Â else > Â Â # It's not a hash, do stuff with it! > Â end > end > > my_hash.each { |obj| iteration(obj) } > Oops. I fixed line 3 above :) -Jonathan Nielsen
From: Xavier Noria on 24 Feb 2010 16:56 On Wed, Feb 24, 2010 at 10:40 PM, Glenn Ritz <glenn_ritz(a)yahoo.com> wrote: > I'd like to be able to take a hash whose values are either hashes or > some other object. If the values are hashes, I'd like to iterate over > them and keep this up until the values aren't hashes. Â And I won't know > how many level there will be until the program is running. Â Any > suggestions? The iterator should yield... what? key, value pairs when it gets to a leave? Only values? All pairs no matter the type of the value?
From: Jonathan Nielsen on 24 Feb 2010 16:58 > Hi, > > I'd like to be able to take a hash whose values are either hashes or > some other object. If the values are hashes, I'd like to iterate over > them and keep this up until the values aren't hashes. Â And I won't know > how many level there will be until the program is running. Â Any > suggestions? > def iteration obj if obj.is_a? Hash iteration obj else # It's not a hash, do stuff with it! end end my_hash.each { |obj| iteration(obj) } ^^ Probably not the best way, but it works... -Jonathan Nielsen
From: Robert Klemme on 24 Feb 2010 17:04 2010/2/24 Jonathan Nielsen <jonathan(a)jmnet.us>: >> >> def iteration obj >> if obj.is_a? Hash >> obj.each { |new_obj| iteration(new_obj) } >> else >> # It's not a hash, do stuff with it! >> end >> end >> >> my_hash.each { |obj| iteration(obj) } >> > > Oops. I fixed line 3 above :) You could also do def iter(h,&b) h.each do |k,v| case v when Hash iter(v,&b) else b[v] end end end iter my_hash do |obj| p obj end Although the disadvantage is that doing it this way the structure information cannot be evaluated in the block. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/
|
Next
|
Last
Pages: 1 2 Prev: Ocra: "Failed to create directory" Next: WWW deprecation notice in Mechanize |