programing

Ruby <=> (로컬) 연산자란 무엇입니까?

css3 2023. 6. 9. 22:17

Ruby <=> (로컬) 연산자란 무엇입니까?

루비란 무엇입니까?<=>교환원?연산자가 다른 언어로 구현되어 있습니까?

우주선 조종사가 돌아올 것입니다.1,0또는−1오른쪽 인수에 상대적인 왼쪽 인수의 값에 따라 달라집니다.

a <=> b :=
  if a < b then return -1
  if a = b then return  0
  if a > b then return  1
  if a and b are not comparable then return nil

일반적으로 데이터 정렬에 사용됩니다.

삼원 비교 연산자라고도 합니다.Perl은 아마도 그것을 사용한 최초의 언어일 것입니다.이를 지원하는 다른 언어로는 Apache Groovy, PHP 7+, C++20 등이 있습니다.

우주선 방법은 자신의 클래스에서 정의하고 비교 가능 모듈을 포함할 때 유용합니다.그러면 당신의 수업은>, < , >=, <=, ==, and between?무료의 방법

class Card
  include Comparable
  attr_reader :value

  def initialize(value)
    @value = value
  end

  def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other
    self.value <=> other.value
  end

end

a = Card.new(7)
b = Card.new(10)
c = Card.new(8)

puts a > b # false
puts c.between?(a,b) # true

# Array#sort uses <=> :
p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>]

일반적인 비교 연산자입니다.수신기가 인수보다 작거나 같거나 큰지 여부에 따라 -1, 0 또는 +1을 반환합니다.

간단한 예를 들어 설명하겠습니다.

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

    Ruby는 왼쪽에서 두 배열의 각 요소를 비교하기 시작합니다. 1왼쪽 배열이 다음보다 작을 경우2오른쪽 배열의따라서 왼쪽 배열이 오른쪽 배열보다 작습니다.출력은 다음과 같습니다.-1.

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

    위와 같이 두 번째 요소를 비교하는 것보다 같은 첫 번째 요소를 먼저 비교합니다. 이 경우 왼쪽 배열의 두 번째 요소가 더 크기 때문에 출력은 다음과 같습니다.1.

이 연산자는 비교를 정수 식으로 줄이기 때문에 여러 열/속성을 기준으로 오름차순 또는 내림차순을 정렬하는 가장 일반적인 방법을 제공합니다.

예를 들어 개체 배열이 있으면 다음과 같은 작업을 수행할 수 있습니다.

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end

이 기본 패턴은 각 열에 대한 오름차순/하강 순열에서 열 수에 따라 정렬되도록 일반화할 수 있습니다.

뭐가<=>('우주선' 운영자)

운영자를 소개한 RFC에 따르면 $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

예:

//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

추가 정보:

// 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

언급URL : https://stackoverflow.com/questions/827649/what-is-the-ruby-spaceship-operator