Hash Sorting

Gary W. wrote:

On Jan 30, 2008, at 1:39 AM, Nico Ritsche wrote:

all.
Can you cut, paste, and post the snippit of code you are using to
display your incorrect results?

I diplay the result like this (in a rails rhtml.file, so there are
actually <% %> around the statements):

pi_array_sorted.each do |a|
a[0].titleize

… some other code …

end

Well, maybe I need to strip down the example a bit, and test it with
simpler hashs without nested arrays as values. I suspect that the nested
arrays could be the problem…

Ilan B. wrote:

But this is not what I get. The keys in the resulting array still have
an arbitrary order, the exact same order as if I don’t call .sort at
all.

Nico

That is what I assumed, check out my earlier solution and that will work
for you… It will convert a hash of unsorted arrays to a sorted array of
sorted arrays…

hth

ilan

You mean this one?

irb(main):002:0> a = {1=>[3,7,1,7], 2=>[3,7,1,1],3=>[3,2,2,9]}
=> {1=>[3, 7, 1, 7], 2=>[3, 7, 1, 1], 3=>[3, 2, 2, 9]}
irb(main):003:0> a.each {|b,c| c.sort!}
=> {1=>[1, 3, 7, 7], 2=>[1, 1, 3, 7], 3=>[2, 2, 3, 9]}
irb(main):004:0> a.sort
=> [[1, [1, 3, 7, 7]], [2, [1, 1, 3, 7]], [3, [2, 2, 3, 9]]]

Well, as I said my focus is on sorting the keys, not the nested arrays,
although I might need to do that as well later. But this solution
doesn’t work
in my case, as I pointed out. I call hash.sort, directly, which is
equivilant to omiting your nested array search (a.each {|b,c| c.sort!})
which doesn’t have anything to do with sorting the keys anyway, it only
sorts the values, i.e. the nested arrays. a.sort doesn’t sort the keys
in my example for some reason.

But this is not what I get. The keys in the resulting array still have
an arbitrary order, the exact same order as if I don’t call .sort at
all.

Nico

That is what I assumed, check out my earlier solution and that will work
for you… It will convert a hash of unsorted arrays to a sorted array of
sorted arrays…

hth

ilan

Jon Egil Stand wrote:

If you have a Hash like this
{1=>5, 19=>4, 9=>88}

h.keys.sort
=> [1, 9, 19]

sorts the keys.

All the best
Jon Egil

Yipee, this finally works! Thanks Jon!

I simply had to sort the keys and the iterate ofer the sorted keys,
using the keys for indexing into the hash:

@sorted_keys = @parent_items.keys.sort

then

@sorted_keys.each do |key|
@parent_items[key].do_whatever
key.do_whatever
end

Easy, but still wonder why the other solutions don’t work…

If you have a Hash like this
{1=>5, 19=>4, 9=>88}

h.keys.sort
=> [1, 9, 19]

sorts the keys.

All the best
Jon Egil