Thread: Sorting

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2008
    Location
    Melbourne
    Posts
    11
    Rep Power
    0

    Question Sorting


    Hi,

    Does anyone have the idea of how 'sort' function is implemented in the class 'Array'?


    Thanks!!!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2008
    Posts
    41
    Rep Power
    42
    I know Ruby code isn't exactly fully documented, but its always worth a look.. Here is what the Array#sort docs say:

    Returns a new array created by sorting self. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1. See also Enumerable#sort_by.

    a = [ "d", "a", "e", "c", "b" ]
    a.sort #=> ["a", "b", "c", "d", "e"]
    a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]

    Unless there was more to your question, as the docs say, sort uses the <=> operator or a block. Not sure if this answers your question or not. If not you may have to elaborate

    Comments on this post

    • Joseph Taylor agrees
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2008
    Location
    Melbourne
    Posts
    11
    Rep Power
    0

    Smile


    Originally Posted by h4z3
    I know Ruby code isn't exactly fully documented, but its always worth a look.. Here is what the Array#sort docs say:

    Returns a new array created by sorting self. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1. See also Enumerable#sort_by.

    a = [ "d", "a", "e", "c", "b" ]
    a.sort #=> ["a", "b", "c", "d", "e"]
    a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]

    Unless there was more to your question, as the docs say, sort uses the <=> operator or a block. Not sure if this answers your question or not. If not you may have to elaborate


    Thank you !!!

IMN logo majestic logo threadwatch logo seochat tools logo