Representing negative numbers in Ruby
This repo accompanies the article “Representations count”.
It contains a challenge: how would you add support for negative numbers on a (hypothetical) computer which only has natural numbers built in?
In practice, that means implementing the constructor, factory methods and
instance methods of the
SignedNumber class. That
class includes a refinement which discourages you
from accidentally using negative numbers.
git clone https://github.com/tomstuart/negative-numbers.git
bundle exec rspec
lib/signed_number.rbto make the next failing test pass
- If more failing tests remain, go to 4
One way to solve this challenge is to represent a signed number as the
combination of a “sign” (positive or negative) and a “size” (absolute
magnitude). See the
for a worked solution.
The first representation is easier to understand, but the second is arguably easier to implement correctly.