Exception Handling/Divide By Zero/NaN Done on One Line

J

John Kopanas

I have the following:

a = (y != 0) ? (x/y) : 0

There must be a sexier way of doing this! Any suggestions?

On a side note... how do we do exception handling on the same line as statement?

a = x/y rescue 0

That does not work but does it make sense? Is it because dividing by
zero does not throw an exception?

Thanks for your help! :)

Your Friend,

John

--
John Kopanas
(e-mail address removed)

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info
 
A

ara.t.howard

I have the following:

a = (y != 0) ? (x/y) : 0

There must be a sexier way of doing this! Any suggestions?

On a side note... how do we do exception handling on the same line as
statement?

a = x/y rescue 0

That does not work but does it make sense? Is it because dividing by
zero does not throw an exception?

Thanks for your help! :)

works for me?

harp:~ > ruby -e' a = 42/0 rescue 42; p a '
42

i think you're doing the right thing with
a = x/y rescue 0

how doesn't it work?

regards.

-a
 
R

Rob Biedenharn

works for me?

harp:~ > ruby -e' a = 42/0 rescue 42; p a '
42

i think you're doing the right thing with


how doesn't it work?

regards.

-a
--
we can deny everything, except that we have the possibility of
being better.
simply reflect on that.
- the dalai lama

If you're not limited to Integers:
ZeroDivisionError: divided by 0
from (irb):1:in `/'
from (irb):1
If either x or y are Float, then dividing by zero isn't an exception.

You could force an exception if you want to get back to an Integer:
FloatDomainError: Infinity
from (irb):7:in `to_i'
from (irb):7FloatDomainError: NaN
from (irb):8:in `to_i'
from (irb):8

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 
J

John Kopanas

I need to keep it as a float... that is my problemo :-(.

If you're not limited to Integers:

ZeroDivisionError: divided by 0
from (irb):1:in `/'
from (irb):1

If either x or y are Float, then dividing by zero isn't an exception.

You could force an exception if you want to get back to an Integer:

FloatDomainError: Infinity
from (irb):7:in `to_i'
from (irb):7
FloatDomainError: NaN
from (irb):8:in `to_i'
from (irb):8

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)


--
John Kopanas
(e-mail address removed)

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top