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

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

    When you have an array of, let's say, integers to sort, it's pretty straightforward for sort method to order the elements properly - smaller numbers first, bigger at the end. That's when you use ordinary sort, with no block.

    But when you are sorting other objects, it may be needed to provide a way to compare (each) two of them. Let's say you have an array of objects of class Person. You probably can't tell if object bob is greater than object mike (i.e. class Person doesn't have method <=> implemented). In that case you'd need to provide some code to explain in which order you want these objects sorted to sort method. That's where the block form kicks in.

    people.sort{|p1,p2| p1.age <=> p2.age}
    people.sort{|p1,p2| p1.children.count <=> p2.children.count}
    

    etc. In all these cases, sort method sorts them the same way - the same algorithm is used. What is different is comparison logic.

    0 讨论(0)
提交回复
热议问题