Please Explain Ruby's Square Root (Sqrt) Value Comparison
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...
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
3 Answers
Math.sqrt(x ** 2 + y ** 2) is using good old Pythagoras to calculate the Cartesian distance of the vector's endpoint from the origin, i.e., the length of the vector. For v1 this is 6.324555320336759, and for v2 the result is 5.656854249492381.
To inspect a Ruby object use p rather than puts.
p v2 # <Vector:0x0000000109a1eb40 @x=4, @y=-4>
what are the resulting values for v1 and v2?
Override to_s
class Vector
def to_s
"x = #{x} : y = #{y} : scalar = #{'%.6f' % scalar}"
end
end #Vector
And you get this output:
puts v1 # => x = 2 : y = 6 : scalar = 6.324555
puts v2 # => x = 4 : y = -4 : scalar = 5.656854
scalar would be better named magnitude because it is calculating the length of a vector using the Pythagorean Theorem. If you are unfamiliar with vectors and Pythagorean Theorem, I suggest you study the mathematical concepts here before you continue with much more code. Those concepts will be critical in understanding how they are used in code.