Menu
Coddy logo textTech

Operator Methods

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 38 of 57.

Most Ruby operators are methods. a + b calls a.+(b), so a class defines + like any other method. Arithmetic on value objects returns a new object and leaves both operands unchanged:

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)

The right operand can be another kind of value, such as a number for scaling. Unary minus is the 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)

Once + exists, += works too, because a += b means a = a + b. sum also works when given a starting value of your class:

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

<=> is an operator too. Together with Comparable, it lets Money objects be compared and sorted, and an operator can refuse a mismatched operand by raising, like numbers do:

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

Challenge

Easy

Complete the class Vector. Define + and - for two vectors, * for a vector and a number, unary minus -@, == comparing both coordinates, and to_s, which returns (4, 6). length returns the vector's length with Math.sqrt.

The supplied code reads expressions: 1,2 + 3,4, 1,2 - 3,4, 1,2 * 3, neg 1,2 and 1,2 == 1,2. It prints each result, and for vector results also length 7.21 with two decimals.

Your code goes in vector.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'vector'

# Supplied input/output code: keep it as it is
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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Ruby compiler