This is a card in Dave's Virtual Box of Cards.

Using Ruby as a Calculator

Page created: 2024-04-10
Draft!
This page is a draft and may be incomplete, incorrect, or just a stub or outline. I've decided to allow myself to put draft pages on my website as an experiment. I'm hoping they will:
  • Help me address my backlog of article ideas.
  • Serve as a "living" TODO list of things to work on.
  • Be useful to myself or others in their incomplete forms.
As always, I'm happy to accept feedback on anything I publish including draft content.

Back to The Ruby Language

The Ruby programming language makes a fantastic command line calculator. I find it much more intuitive to use than tools like bc or dc.

Computers do integer math unless you tell them to do floating point math and many tools and languages reflect this:

bc - the "basic calculator":

$ bc
5 / 3.0
1

Note the integer math, despite dividing by a value with a decimal point.

dc - the RPN "desk calculator":

$ dc
5 3.0 / p
1

Same.

Ruby:

$ irb
> 5 / 3.0
=> 1.6666666666666667
> 5 / 3
=> 1

As you can see, Ruby does what we expect when we give it an explicit floating-point

https://ruby-doc.org/core-2.2.10/Bignum.html

https://ruby-doc.org/core-3.0.2/Rational.html

WORK IN PROGRESS

See also Ruby for "shell scripting"