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 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

5

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>
3

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
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest