Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Sep 23 ’10

Give me Infinity

In Ruby, dividing a kind of Integer (e.g a Fixnum or Bignum) by 0 will result in a ZeroDivisionError. Make the divisor and/or the dividend a float, e.g. 1.0/0, 1/0.0, or 1.0/0.0 and an exception will not be raised, the quotient returned will be Infinity.

It can be quite useful, I used this today for some discount code, i.e. sometimes a discount should never be applied.

ruby-1.9.2-p0 > 1/0
ZeroDivisionError: divided by 0
    from (irb):1:in `/'
    from (irb):1
    from /Users/stevegraham/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
ruby-1.9.2-p0 > 1/0.0
 => Infinity 

For negative Infinity, make the dividend or the divisor negative.

(Source: stevegraham)

21 notes 0 comments (via stevegraham)

  1. atm09td reblogged this from rubyquicktips
  2. rubyquicktips reblogged this from stevegraham
  3. stevegraham posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus