Home > other >  Please explain Ruby's square root (sqrt) value comparison
Please explain Ruby's square root (sqrt) value comparison

Time:02-15

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

CodePudding user response:

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>

CodePudding user response:

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.

CodePudding user response:

Override to_s

def to_s
  "x = #{x} : y = #{y}"
 end

And you get this output:

puts v1    # =>  x = 2 : y = 6
puts v2    # =>  x = 4 : y = -4
  •  Tags:  
  • ruby
  • Related