Iterate HashWithIndifferentAccess

How do I iterate a HashWithIndifferentAccess? I need to set the order
using a sortable_element.

first check out the class of the object, if its a hash do

HashWithIndifferentAccess.each do |key, value|
puts key
puts value
end

On 21 September 2010 21:45, radhames brito [email protected] wrote:

first check out the class of the object, if its a hash do

HashWithIndifferentAccess.each do |key, value|
puts key
puts value
end

if it’s a hash, its order is not guaranteed… next time you iterate
it, you might find it’s in a different order

Pål Bergström wrote:

How do I iterate a HashWithIndifferentAccess? I need to set the order
using a sortable_element.

As Michael said, order is not guaranteed – even if you include an
element for that.

When I need to count on the order I use an array of pairs. I use this
for value list data. It’s not as handy as Lasso’s array of pairs which
are sortable and searchable, but it’s a close as we get.

list = [ [“Small”, “S”], [“Medium”,“M”], [“Large”,“L”] ]

If you have to start with the Hash, and it includes a sort number of
some type, then you can modify the conversion to specifically retrieve
the by the sort number.

If you need help with that, give an exampe of the exact data structure
you’d be starting with.

– gw

Greg W. wrote:

If you need help with that, give an exampe of the exact data structure
you’d be starting with.

With the help of sortable_element and :tree set as true (and moving up
item 3 before item 1, just as a test) I get a Hash from this list:

The hash:

{“0”=>{“id”=>“3”}, “1”=>{“id”=>“1”}, “2”=>{“0”=>{“id”=>“6”}, “id”=>“5”,
“1”=>{“id”=>“7”}}}

I can sort out the key and value. But with key nr 2 I have problem (id 5
with sub list containing id 6). If I use params[:mylist].each do |k,v| I
only get the key of 2 and value 5. How do I deal with a nested hash like
that?

I hope I make sense.

radhames brito wrote:

i hash inside a hash i read it list[:outer_value][:deeper_value] and
you
can do

list.each do |key,value|
if value.class == ‘Hash’
puts “values for key #{ key}”
value.each do | key2,value2|
puts “key: #{key2} and value: #{value2}”
end
else
puts “key: #{key} and value: #{value}”
end
end

Perfect. Thanks.

i hash inside a hash i read it list[:outer_value][:deeper_value] and
you
can do

list.each do |key,value|
if value.class == ‘Hash’
puts “values for key #{ key}”
value.each do | key2,value2|
puts “key: #{key2} and value: #{value2}”
end
else
puts “key: #{key} and value: #{value}”
end
end

2010/9/22 PÃ¥l Bergström [email protected]