Menu
Coddy logo textTech

연산자 메서드

Coddy Ruby 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 38번째.

Ruby 연산자의 대부분은 메서드입니다. a + b는 a.+(b)를 호출하므로, 클래스는 다른 메서드와 마찬가지로 +를 정의합니다. 값 객체에 대한 산술 연산은 새로운 객체를 반환하고 두 피연산자를 모두 변경하지 않은 상태로 둡니다:

class Vector
  attr_reader :x, :y

  def initialize(x, y)
    @x = x
    @y = y
  end

  def +(other)
    Vector.new(x + other.x, y + other.y)
  end

  def to_s
    "(#{x}, #{y})"
  end
end

a = Vector.new(1, 2)
b = Vector.new(3, 4)
puts a + b
puts a

출력:

(4, 6)
(1, 2)

오른쪽 피연산자는 크기 조정을 위한 숫자처럼 다른 종류의 값일 수도 있습니다. 단항 마이너스는 -@ 메서드입니다:

class Vector
  attr_reader :x, :y

  def initialize(x, y)
    @x = x
    @y = y
  end

  def -(other)
    Vector.new(x - other.x, y - other.y)
  end

  def *(factor)
    Vector.new(x * factor, y * factor)
  end

  def -@
    Vector.new(-x, -y)
  end

  def to_s
    "(#{x}, #{y})"
  end
end

v = Vector.new(3, 4)
puts v * 2
puts v - Vector.new(1, 1)
puts(-v)

출력:

(6, 8)
(2, 3)
(-3, -4)

+가 존재하면 +=도 작동합니다. a += b는 a = a + b를 의미하기 때문입니다. 클래스의 시작 값을 제공하면 sum도 작동합니다.

class Money
  attr_reader :cents

  def initialize(cents)
    @cents = cents
  end

  def +(other)
    Money.new(cents + other.cents)
  end

  def to_s
    format("$%.2f", cents / 100.0)
  end
end

total = Money.new(0)
total += Money.new(250)
total += Money.new(199)
puts total
puts [Money.new(100), Money.new(5)].sum(Money.new(0))

출력:

$4.49
$1.05

<=>도 연산자입니다. Comparable과 함께 사용하면 Money 객체를 비교하고 정렬할 수 있으며, 연산자는 숫자처럼 예외를 발생시켜 일치하지 않는 피연산자를 거부할 수도 있습니다:

class Money
  include Comparable
  attr_reader :cents, :currency

  def initialize(cents, currency)
    @cents = cents
    @currency = currency
  end

  def +(other)
    raise ArgumentError, "cannot add #{other.currency} to #{currency}" unless other.currency == currency

    Money.new(cents + other.cents, currency)
  end

  def <=>(other)
    cents <=> other.cents
  end
end

puts Money.new(500, "EUR") > Money.new(300, "EUR")
begin
  Money.new(1, "EUR") + Money.new(1, "USD")
rescue ArgumentError => e
  puts e.message
end

출력:

true
cannot add USD to EUR
challenge icon

챌린지

쉬움

Vector 클래스를 완성하세요. 두 벡터에 대해 +와 -를 정의하고, 벡터와 숫자에 대해 *를 정의하며, 단항 빼기 -@, 두 좌표를 모두 비교하는 ==, 그리고 (4, 6)을 반환하는 to_s를 정의하세요. length는 Math.sqrt를 사용해 벡터의 길이를 반환합니다.

제공된 코드는 다음 표현식을 읽습니다: 1,2 + 3,4, 1,2 - 3,4, 1,2 * 3, neg 1,2 및 1,2 == 1,2. 각 결과를 출력하며, 벡터 결과의 경우 소수점 이하 두 자리로 length 7.21도 출력합니다.

코드는 vector.rb에 작성하세요. main.rb에는 제공된 입력/출력 코드가 포함되어 있으며 수정할 수 없습니다.

직접 해보기

require_relative 'vector'

# 제공된 입/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
  input << line.chomp
end
def vec(text)
  Vector.new(*text.split(",").map(&:to_i))
end

input.each do |line|
  parts = line.split
  result = if parts[0] == "neg" then -vec(parts[1])
           else
             a = vec(parts[0])
             case parts[1]
             when "+" then a + vec(parts[2])
             when "-" then a - vec(parts[2])
             when "*" then a * parts[2].to_i
             else a == vec(parts[2])
             end
           end
  puts result
  puts format("length %.2f", result.length) if result.is_a?(Vector)
end
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Ruby 컴파일러