find the distance between two points in ruby

To find the distance between two points in ruby, we need to use the distance formula from analytic geometry. The formula to find the distance between two points p1(x1, y1) and p2(x2, y2) is:

main.rb
distance = sqrt((x2 - x1)**2 + (y2 - y1)**2)
45 chars
2 lines

In ruby, we can implement this formula in a method like this:

main.rb
def distance_between_points(x1, y1, x2, y2)
  Math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
end
89 chars
4 lines

Here, we have defined a method named distance_between_points that takes four arguments as the x and y coordinates of the two points. Inside the method, we have used the distance formula and returned the calculated distance.

We can use this method in our program to find the distance between any two points. For example:

main.rb
distance = distance_between_points(1, 2, 4, 6)
puts "The distance between the points is #{distance}"
101 chars
3 lines

This will output:

main.rb
The distance between the points is 5.0
39 chars
2 lines

Here, we have called the distance_between_points method with the x and y coordinates of two points (1,2) and (4,6) respectively. The method has calculated the distance between these points and returned the result, which we have assigned to the distance variable. Finally, we have printed the result using puts statement.

gistlibby LogSnag