Jason Raymond
Jason Raymond

Reputation: 33

ZeroDivisionError in Ruby Program

I am trying to teach myself Ruby using "Computer Science Programming Basics in Ruby" and other sources. I am stuck on a question and this book does not provide solutions.

The exercise is to write a program that given two points on a 2d graph outputs a message describing the line (horizontal or vertical) or it's slope (positive or negative). This is what I have so far.

# Get the first point from a user
puts "Please enter Point A's X value."
x_1 = gets.to_i
puts "Please enter Point A's Y value."
y_1 = gets.to_i

# Get the second point from a user
puts "Please enter Point B's X value."
x_2 = gets.to_i
puts "Please enter Point B's Y value."
y_2 = gets.to_i

slope = ((y_1-y_2) / (x_1-x_2))


#Check to see if the line is vertical or horizontal and the slope is +ve or -ve
case 
when (slope == 0) then
puts "The line is horizontal."
when (slope > 0) then
puts "The slope is positive."
when (slope < 0) then
puts "The slope is negative."
when (x_1-x_2 == 0) then
puts "The line is vertical."
end

How would I make a value that is divided by zero return puts "The line is vertical!" without getting the ZeroDivisionError ?

Upvotes: 0

Views: 671

Answers (4)

Matt
Matt

Reputation: 20776

Replace all to_i with to_f. Then you can test for a vertical line with slope.abs == Float::INFINITY.

For completeness, include the test slope.nan? as the first test to output Those are not two distinct points! This will cover the case when they enter in the same point twice.

Upvotes: 2

JeremyS
JeremyS

Reputation: 437

One way to do this is to follow your equation with a rescue, such as

2/0 # this throws an error

2/0 rescue "This line is vertical" # this prints the rescue

2/2 rescue "This line is vertical" # this prints 1

Upvotes: 0

diclophis
diclophis

Reputation: 2442

You can also rescue divide by zero operations in ruby

begin
  1/0
rescue ZeroDivisionError => kaboom
  p kaboom
end

Upvotes: 0

Alexandre Abreu
Alexandre Abreu

Reputation: 1417

x == 0 ? puts "The line is vertical!" : y/x

Upvotes: 0

Related Questions