Distance from a point to a line in Ruby
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Hi,

I want the Ruby code for calculating the distance from a point to a line (calculate(point, line))

A point should be represented as a hash with x and y keys. X and Y components are integers.

A line should be represented by a hash containing two points, keyed with a and b.

Thanks!

awarded to alex
Tags
ruby

Crowdsource coding tasks.

1 Solution

Winning solution

This function should work for you

def calculate(point,line)
    # get all the vars, cuz it's easier to handle
    lineaX = line[:a][:x]
    lineaY = line[:a][:y]

    linebX = line[:b][:x]
    linebY = line[:b][:y]

    lengthAB = hypot(linebX - lineaX, linebY - lineaY)
    return (((point["x"] - lineaX) * (linebY - lineaY) - (point["y"] - lineaY) * (linebX - lineaX)).abs) / lengthAB
end

def hypot(sideA, sideB)
    return(Math.sqrt(sideA**2 + sideB**2))
end

with usage as follows:

#!/usr/bin/ruby

point = Hash.new
    point["x"] = 0
    point["y"] = 0

line = {
    :a => {
        :x => 0,
        :y => 1
    },
    :b => {
        :x => 1,
        :y => 0
    }
}

def calculate(point,line)
    # get all the vars, cuz it's easier to handle
    lineaX = line[:a][:x]
    lineaY = line[:a][:y]

    linebX = line[:b][:x]
    linebY = line[:b][:y]

    lengthAB = hypot(linebX - lineaX, linebY - lineaY)
    return (((point["x"] - lineaX) * (linebY - lineaY) - (point["y"] - lineaY) * (linebX - lineaX)).abs) / lengthAB
end

    def hypot(sideA, sideB)
        return(Math.sqrt(sideA**2 + sideB**2))
    end

print calculate(point,line)
print "\n"