From: Glenn Ritz on
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
>
> 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
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
> 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
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/