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

前端 未结 7 1703
北海茫月
北海茫月 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:44

    <=> is a method is ruby that returns ( self.<=>( argument ) )

    • -1 if self < argument
    • 0 if self == argument
    • 1 if self > argument

    x and y are items of array. If no block is provided, the sort function uses x<=>y, otherwise the result of the block says if x should be before y.

    array.sort{|x, y| some_very_complicated_method(x, y) }
    

    Here if some_very_complicated_method(x, y) returns smth that is < 0, x is considered < than y and so on...

提交回复
热议问题