Chapter 17. Calculator

In this chapter we’ll look at a small calculator.[1] This one has two twists. One is that it’s based on a stack like an old HP calculator. The second is that it knows units.

[1] The source code for this example is at http://github.com/kevinrutherford/rrwb-code.

image

The stack approach lets us avoid dealing with the challenges of parsing (and tricky things like parentheses). It works like this: You can push values, and an operator such as + pops the top two items off the stack and replaces them with the sum. For example, 3 + 4 5 would be done with “3 PUSH 4 PUSH 5*+” whereas 3 4 + 5 would be “3 PUSH 4 * PUSH 5 +” and (3 + ...

Get Refactoring in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.