Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Newbie Hint for the day: .keys.sort

Reply
Thread Tools

Newbie Hint for the day: .keys.sort

 
 
John Carter
Guest
Posts: n/a
 
      10-09-2005
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 : http://www.velocityreviews.com/forums/(E-Mail 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.


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
PIX VPN debugging hint Walter Roberson Cisco 0 10-18-2005 04:56 AM
How to create a hint? Marek ASP .Net 5 12-27-2004 04:13 PM
RE: newbie: confused with example in Learning Python 2nd Edition:cananyone give a hint Robert Brewer Python 4 08-24-2004 06:40 AM
newbie: confused with example in Learning Python 2nd Edition: can anyone give a hint Porky Pig Jr Python 3 08-24-2004 04:02 AM
can anyone give me a hint Robert MCSD 0 08-11-2004 05:49 PM



Advertisments