Hash Sorting

N

Nico Ritsche

Gary said:
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...
 
I

Ilan Berci

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
 
N

Nico Ritsche

Ilan said:
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.
 
J

Jon Egil Stand

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

sorts the keys.


All the best
Jon Egil
 
N

Nico Ritsche

Jon said:
If you have a Hash like this
{1=>5, 19=>4, 9=>88}
=> [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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top