Menu
CoddyTech

Operator method

Termasuk bagian Pemrograman Berorientasi Objek dalam perjalanan Ruby di Coddy. Pelajaran 38 dari 57.

Sebagian besar operator Ruby adalah method. a + b memanggil a.+(b), jadi sebuah class mendefinisikan + seperti method lainnya. Operasi aritmetika pada object nilai menghasilkan object baru dan membiarkan kedua operand tetap tidak berubah:

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

Output:

(4, 6)
(1, 2)

Operand kanan bisa berupa jenis nilai lain, seperti angka untuk penskalaan. Minus unary adalah method -@:

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)

Output:

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

Setelah + tersedia, += juga berfungsi, karena a += b berarti a = a + b. sum juga berfungsi jika diberi nilai awal dari class-mu:

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

Output:

$4.49
$1.05

<=> juga merupakan operator. Bersama Comparable, operator ini memungkinkan object Money dibandingkan dan diurutkan, dan operator dapat menolak operand yang tidak cocok dengan memunculkan error, seperti yang dilakukan angka:

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

Output:

true
cannot add USD to EUR
challenge icon

Tantangan

Mudah

Lengkapi class Vector. Definisikan + dan - untuk dua vector, * untuk sebuah vector dan angka, tanda minus unary -@, == untuk membandingkan kedua koordinat, serta to_s, yang mengembalikan (4, 6). length mengembalikan panjang vector menggunakan Math.sqrt.

Code yang disediakan membaca ekspresi: 1,2 + 3,4, 1,2 - 3,4, 1,2 * 3, neg 1,2 dan 1,2 == 1,2. Code tersebut mencetak setiap hasil, dan untuk hasil berupa vector juga mencetak length 7.21 dengan dua angka desimal.

Tulis kodemu di vector.rb. main.rb berisi code input/output yang disediakan dan tidak boleh diedit.

Coba sendiri

require_relative 'vector'

# Kode input/output yang disediakan: biarkan apa adanya
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 iconUji dirimu

Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.

Semua pelajaran di Pemrograman Berorientasi Objek

Latihan sendiri: Compiler Ruby online