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.rb45 chars2 lines
In ruby, we can implement this formula in a method like this:
main.rb89 chars4 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.rb101 chars3 lines
This will output:
main.rb39 chars2 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