irb: The New Desktop Calculator

One of the things I love about Ruby is that it comes with irb. It is short for Interactive Ruby, and it is a command line tool to interact with an instance of the Ruby interpreter. To start it up just run irb from the command line (Interactive Ruby is a menu option in the most common Windows Ruby package). One of my most frequent uses of irb is as a calculator:

irb(main):001:0> 1465 + 1723
=> 3188

Simple addition is not too exciting, but that’s just the beginning. When Ruby is at your fingertips, the sky is the limit (limited by your imagination, of course). You can sum up a whole list of numbers quickly:

irb(main):002:0> [1, 2, 3, 4, 5, 6].inject(0) { |x, y| x + y }
=> 21

Use variables to store values or add to them:

irb(main):003:0> a = 515
=> 515
irb(main):004:0> a += 23
=> 538

Or perhaps you need a special function to crunch your numbers today? Just define it, possibly as an instance method for the Array or Integer classes, and then have a blast with it:

irb(main):005:0> class Array
irb(main):006:1>   def sum_of_squares
irb(main):007:2>     inject(0) { |s, x| s + x * x }
irb(main):008:2>   end
irb(main):009:1> end
=> nil
irb(main):010:0> [1, 2, 3, 4, 5, 6].sum_of_squares
=> 91

Take advantage of some mathematical constants! They are available, too, using the Ruby constants shown below.

irb(main):011:0> Math::PI
=> 3.14159265358979
irb(main):012:0> Math::E
=> 2.71828182845905

Finally, there is just one thing to note. If you are doing division and want a decimal point in your results then you need to make sure you are using at least one floating point precision number in your statement (otherwise the result is an integer dividend):

irb(main):013:0> 2352.0 / 17
=> 138.352941176471
irb(main):014:0> 2352 / 17
=> 138

Using irb as a desktop calculator is really just scratching the surface of what one can do, but I think it is a rather cool application of it. If you have never used irb, or even Ruby, go ahead and give it a try! I hope you find it just as useful as I do.

  • You can skip to the end and leave a comments. Trackback is currently closed.
  • Trackback URI:
  • Comments RSS 2.0

Leave a Reply

You must be logged in to post a comment.