Newbie Hint for the day: .keys.sort

J

John Carter

If, like me, you make heavy use of the ruby Hash type, you quite likely to
make use of the .keys or .each_key method.

nice = {'a'=>1, 'b'=>2, 'c'=>3}
p nice.keys

Results in...

["a", "b", "c"]

That looks all nice and orderly.

Except that's not guaranteed. Consider this example..
b = {'upkpgn'=>1,
'jmay'=>2,
'vkvxxm'=>3}
p b.keys
["upkpgn", "vkvxxm", "jmay"]

Whoops! That didn't come out ordered at all! In fact the order it comes
out in is entirely up to the deeper mysteries, inner feelings, and past
history of the objects hash function, the Hash class and that hash
instance.

Thus unless I'm concerned about speed, and especially when I'm creating
output my standard idiom is instead of using .keys, I always use
keys.sort and instead of .each_key I use .keys.sort.each

Instead of .values, or .each_value I use .values.sort or
values.sort.each or perhaps hash.keys.sort.collect{|k| hash[k]}

And even if you don't care what order it comes out in, your users will be
moaning.

You will get complaints that when they ran a very slightly different
version of your software, or even the same software on a very slightly
different dataset, they got wildly different answers.

Ok, the difference will probably only be in the sort order, but as far as
the user is concerned "WAAAAH!! __EVERYTHING__ Changed!!!! Your software
is just _so_ BROKEN!!"


John Carter Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : (e-mail address removed)
New Zealand

Carter's Clarification of Murphy's Law.

"Things only ever go right so that they may go more spectacularly wrong later."

From this principle, all of life and physics may be deduced.
 

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

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top