Operators for your own classes
Here is a little secret of Ruby's: 1 + 2 is really a method call. The number 1 receives the message + with the argument 2 – Ruby just lets you use the prettier spelling. The same goes for *, ==, < and even the square brackets:
p 1.+(2)
p "bacon".*(3)
p [10, 20, 30].[](1)
5.==(5)And a method is something you can write for your own classes. Chunky is planning hops on a map: 2 squares to the right and 1 up, then 1 to the right and 3 up. Two hops one after the other are like one big one – you add up the x's and the y's. In mathematics such a thing is called a vector. With def +(other), Hop gets a plus, with def *(number) a times:
class Hop
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def +(other)
Hop.new(x + other.x, y + other.y)
end
def *(number)
Hop.new(x * number, y * number)
end
end
far = Hop.new(2, 1) + Hop.new(1, 3)
p [far.x, far.y]
Hop.new(2, 1) * 3Both return a new hop and leave the old ones as they are – just as 1 + 2 doesn't change the 1. Only the => line is ugly: #<Hop:0x… @x=6, @y=3>. Two methods decide what an object looks like as text. to_s from lesson 43 is for people: puts and "#{…}" ask for it. inspect is for programmers: p and the => line ask for it. And you may open a class again at any time and write more methods into it:
class Hop
def to_s
"#{x} right, #{y} up"
end
def inspect
"#<Hop #{x}|#{y}>"
end
end
big = Hop.new(2, 1) * 3
puts "Chunky hops #{big}."
p bigNow turn the sum round: 3 * Hop.new(2, 1). The same thing to us – but to Ruby it's 3.*(…), the method * of the number 3. And that one knows nothing about hops:
3 * Hop.new(2, 1)TypeError: Hop can't be coerced into Integer – the number doesn't know what to do with a hop. An operator always belongs to the object to its left. (In such a case Ruby asks the object on the right for help as well, with a method called coerce. That's something for later; hop * 3 works, after all.)
Next question: are two hops with the same numbers equal? Out of the box, == checks the same thing as equal? from lesson 43: whether it is the same object. For a hop, though, the values are what counts. So you write == yourself – and != comes with it for free:
class Hop
def ==(other)
other.is_a?(Hop) && x == other.x && y == other.y
end
end
short = Hop.new(1, 2)
again = Hop.new(1, 2)
p short.equal?(again) # two different objects ...
p short == again # ... with the same values
short != Hop.new(2, 1)The other.is_a?(Hop) up front makes sure that a comparison with something else entirely – short == 5 – is simply false instead of an error. Nearly done! Only, hashes and uniq don't ask == at all. A hash sorts its keys into drawers by a number that hash works out, and inside the drawer it compares with eql?. Without these two methods, every new Hop.new(1, 2) would be a stranger to a hash. So equal objects need the same number – the easiest is to take the one of [x, y]. And alias eql? == gives == the second name eql?:
class Hop
alias eql? ==
def hash
[x, y].hash
end
end
targets = { Hop.new(1, 2) => "chicken coop" }
p targets[Hop.new(1, 2)]
[Hop.new(1, 2), Hop.new(1, 2), Hop.new(3, 0)].uniqThat leaves comparing with < and >. You know this from lesson 45: include Comparable and a spaceship operator <=> – and at once you get <, >, between? and clamp, and sort and max can put hops in order. Which hop is the farthest? Chunky counts the squares on the map: right plus up, without the sign, as abs does:
class Hop
include Comparable
def distance
x.abs + y.abs
end
def <=>(other)
distance <=> other.distance
end
end
hops = [Hop.new(3, 1), Hop.new(0, 2), Hop.new(-4, 2)]
p hops.max
p hops.sort
Hop.new(1, 1) < Hop.new(0, 3)Your own == stays in charge, by the way, although Comparable brings one along too: in the line of ancestors, the class's own methods come before the module's. That's why Hop.new(2, 0) == Hop.new(0, 2) is still false, although both are equally far.
Finally, the square brackets: with def [](i) a hop answers like an array, 0 for x and 1 for y:
class Hop
def [](i)
[x, y][i]
end
end
hop = Hop.new(5, -2)
p hop[0]
p hop[1]
hop[2]hop[2] is nil, as with an array, because [] simply passes the question on to [x, y]. A rule of thumb: give your class an operator when it is as natural for its objects as it is for numbers – adding up hops, comparing amounts of money. Let it return a new object instead of changing the old one. Whoever writes == writes eql? and hash along with it. And a good inspect makes every bug hunt easier.
Money for amounts in Swiss francs. It counts in cents (hundredths of a franc), because decimal numbers aren't quite exact in a computer (the 0.30000000000000004 from lesson 2): Money.new(450) is 4.50 francs. It needs attr_reader :cents, a + that returns a new Money, a to_s that gives "4.50 CHF", and an == that calls two amounts with the same cents equal. Then even sum can add up your shopping.# class Money
# attr_reader :cents
# ... # initialize(cents), +(other), to_s ("4.50 CHF"), ==(other)
# end
# shopping = [Money.new(450), Money.new(120), Money.new(230)]
# puts shopping.sum(Money.new(0))"1.10.0" can't be compared as strings: "1.10.0" > "1.9.2" is false, because strings are compared character by character, and "1" comes before "9". Write VersionNumber: VersionNumber.new("1.10.0") remembers the text, to_s returns it, and with include Comparable and a <=> that compares the parts as numbers, VersionNumber.new("1.10.0") > VersionNumber.new("1.9.2") becomes true.# class VersionNumber
# include Comparable
# ... # initialize(text), to_s, parts ([1, 10, 0]), <=>(other)
# end
# VersionNumber.new("1.10.0") > VersionNumber.new("1.9.2")