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

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

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

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 15:32

    What is <=> ( The 'Spaceship' Operator )

    According to the RFC that introduced the operator, $a <=> $b

     -  0 if $a == $b
     - -1 if $a < $b
     -  1 if $a > $b
    

     - Return 0 if values on either side are equal
     - Return 1 if value on the left is greater
     - Return -1 if the value on the right is greater
    

    Example:

    //Comparing Integers
    
    echo 1 <=> 1; //ouputs 0
    echo 3 <=> 4; //outputs -1
    echo 4 <=> 3; //outputs 1
    
    //String Comparison
    
    echo "x" <=> "x"; // 0
    echo "x" <=> "y"; //-1
    echo "y" <=> "x"; //1
    

    MORE:

    // Integers
    echo 1 <=> 1; // 0
    echo 1 <=> 2; // -1
    echo 2 <=> 1; // 1
    
    // Floats
    echo 1.5 <=> 1.5; // 0
    echo 1.5 <=> 2.5; // -1
    echo 2.5 <=> 1.5; // 1
    
    // Strings
    echo "a" <=> "a"; // 0
    echo "a" <=> "b"; // -1
    echo "b" <=> "a"; // 1
    
    echo "a" <=> "aa"; // -1
    echo "zz" <=> "aa"; // 1
    
    // Arrays
    echo [] <=> []; // 0
    echo [1, 2, 3] <=> [1, 2, 3]; // 0
    echo [1, 2, 3] <=> []; // 1
    echo [1, 2, 3] <=> [1, 2, 1]; // 1
    echo [1, 2, 3] <=> [1, 2, 4]; // -1
    
    // Objects
    $a = (object) ["a" => "b"]; 
    $b = (object) ["a" => "b"]; 
    echo $a <=> $b; // 0
    

提交回复
热议问题