I have a Ruby class that compares the size of two values of x and y by inheriting the built-in module Comparable and sqrt methods. But unfortunately, I don't understand what def scalar
in the code is calculating?
In the example below, Ruby's execution results in that v1 is greater than v2, but if I print the results of v1 and v2 alone, I get nothing but nonsense. So my second question is, what are the resulting values for v1 and v2?
class Vector
include Comparable
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def scalar
Math.sqrt(x ** 2 + y ** 2)
end
def <=> (other)
scalar <=> other.scalar
end
end
v1 = Vector.new(2, 6)
v2 = Vector.new(4, -4)
puts v1 #=> #<Vector:0x000055a6d11794e0>
puts v2 #=> #<Vector:0x000055a6d1179490>
p v1 <=> v2 #=> 1
p v1 < v2 #=> false
p v1 > v2 #=> ture