How does Array#sort work when a block is passed?

前端 未结 7 1706
北海茫月
北海茫月 2020-11-29 18:10

I am having a problem understanding how array.sort{ |x,y| block } works exactly, hence how to use it?

An example from Ruby documentation:



        
7条回答
  •  囚心锁ツ
    2020-11-29 18:51

    In:

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

    what is x and y?

    x and y are the elements being compared by the sorting algorithm.

    This is useful to define for custom classes which element should be before the other.

    For basic data ( numbers, strings , date, etc ) the natural order is predefined, but for customer element ( ie Employee ) you define who goes before who in a comparison. This block give you the chance to define that.

    and what happens at y<=>x?

    There, they are comparing the elements in descending order ( those with "higher" value will go first ) rather than the natural order ( x<=>y )

    The <=> method stands for "compareTo" and return 0 if the elements are equivalent, or < 0 if x goes before than y or > 0 if x goes after y

提交回复
热议问题