What is the Ruby <=> (spaceship) operator?

后端 未结 6 1802
夕颜
夕颜 2020-11-22 14:42

What is the Ruby <=> (spaceship) operator? Is the operator implemented by any other languages?

6条回答
  •  遇见更好的自我
    2020-11-22 15:30

    I will explain with simple example

    1. [1,3,2] <=> [2,2,2]

      Ruby will start comparing each element of both array from left hand side. 1 for left array is smaller than 2 of right array. Hence left array is smaller than right array. Output will be -1.

    2. [2,3,2] <=> [2,2,2]

      As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is 1.

提交回复
热议问题