Menu
Coddy logo textTech

Operatör Metotları

Coddy'nin Ruby Journey'sinin Nesne Yönelimli Programlama bölümünün bir parçası. Ders 38 / 57.

Ruby operatörlerinin çoğu metottur. a + b, a.+(b) çağrısını yapar; bu nedenle bir sınıf, diğer tüm metotlar gibi + metodunu tanımlar. Değer nesneleri üzerinde aritmetik işlem, yeni bir nesne döndürür ve her iki işleneni de değiştirmeden bırakır:

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

Çıktı:

(4, 6)
(1, 2)

Sağ operand, ölçeklendirme için bir sayı gibi başka türde bir değer olabilir. Unary minus, -@ metodudur:

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)

Çıktı:

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

Bir kez + mevcut olduğunda, += de çalışır; çünkü a += b, a = a + b anlamına gelir. sum ayrıca sınıfınızın bir başlangıç değeriyle verildiğinde de çalışır:

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

Çıktı:

$4.49
$1.05

<=> de bir operatördür. Comparable ile birlikte, Money nesnelerinin karşılaştırılmasını ve sıralanmasını sağlar; ayrıca bir operatör, sayıların yaptığı gibi, istisna yükselterek uyumsuz bir işleneni reddedebilir:

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

Çıktı:

true
cannot add USD to EUR
challenge icon

Görev

Kolay

Vector sınıfını tamamla. İki vektör için + ve -, bir vektör ve sayı için *, tekli eksi -@, her iki koordinatı karşılaştıran == ve (4, 6) döndüren to_s tanımla. length, Math.sqrt ile vektörün uzunluğunu döndürür.

Sağlanan kod şu ifadeleri okur: 1,2 + 3,4, 1,2 - 3,4, 1,2 * 3, neg 1,2 ve 1,2 == 1,2. Her sonucu yazdırır; vektör sonuçları için ayrıca iki ondalık basamakla length 7.21 yazdırır.

Kodun vector.rb dosyasına gider. main.rb sağlanan girdi/çıktı kodunu içerir ve düzenlenemez.

Kendin dene

require_relative 'vector'

# Sağlanan girdi/çıktı kodu: olduğu gibi bırakın
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 iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

Nesne Yönelimli Programlama bölümündeki tüm dersler

Kendi başına pratik yap: Online Ruby derleyicisi