Newbie Hint for the day: .keys.sort

Discussion in 'Ruby' started by John Carter, Oct 9, 2005.

  1. John Carter

    John Carter Guest

    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 :
    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.
    John Carter, Oct 9, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Porky Pig Jr
    Replies:
    3
    Views:
    385
    Dave Cole
    Aug 24, 2004
  2. Robert Brewer
    Replies:
    4
    Views:
    384
    Porky Pig Jr
    Aug 24, 2004
  3. Andy
    Replies:
    1
    Views:
    703
  4. Navin
    Replies:
    1
    Views:
    690
    Ken Schaefer
    Sep 9, 2003
  5. John Carter

    Hint for the day: .keys.sort

    John Carter, Mar 2, 2004, in forum: Ruby
    Replies:
    0
    Views:
    90
    John Carter
    Mar 2, 2004
Loading...

Share This Page