Error: undefined method '-' for NIL when running a spec

I’ve implemented the Unary Operators Example:
module Vector
struct Vector2
getter x, y
def initialize(@x : Int32, @y : Int32)
end
# Unary operator. Returns the inverted vector to self.
def - : self
Vector2.new(-x, -y)
end
end
end

v1 = Vector::Vector2.new(1,2)
puts -v1

And it compiles and runs with the expected result: Vector::Vector2(@x=-1, @y=-2)

When I run it as a spec:
require “./spec_helper”

describe Vector do
it “negating a vector” do
v1 = Vector::Vector2.new(1, 2)
-v1.should eq Vector::Vector2.new(-1, -2)
end
end

I get the following error:
In spec/vector_spec.cr:6:5

6 | -v1.should eq Vector::Vector2.new(-1, -2)
^
Error: undefined method ‘-’ for Nil

Is this a bug or something fundamental I’m missing?

I think the issue is that -v1.should eq Vector::Vector2.new(-1, -2) is being treated as -.(v1.should eq Vector::Vector2.new(-1, -2)) of which #should returns Nil. If you re-write the line to be (-v1).should eq Vector::Vector2.new(-1, -2) it works fine.

1 Like

Doh, fundamental misunderstanding it is. Thanks for the quick response. I’ve been beating my head against this for about a day.