Check to see if an array is already sorted?

前端 未结 8 1199
渐次进展
渐次进展 2020-12-17 08:52

I know how to put an array in order, but in this case I just want to see if it is in order. An array of strings would be the easiest, I imagine, and answer

8条回答
  •  -上瘾入骨i
    2020-12-17 09:36

    def ascending? (array)
        yes = true
        array.reduce { |l, r| break unless yes &= (l[0] <= r[0]); l }
        yes
    end
    
    
    def descending? (array)
        yes = true
        array.reduce { |l, r| break unless yes &= (l[0] >= r[0]); l }
        yes
    end
    

提交回复
热议问题