Skip to content

tomstuart/negative-numbers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

Getting started

  1. git clone https://github.com/tomstuart/negative-numbers.git
  2. cd negative-numbers
  3. bundle install
  4. bundle exec rspec
  5. Edit lib/signed_number.rb to make the next failing test pass
  6. If more failing tests remain, go to 4
  7. Celebrate! 🎉

Two solutions

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 sign-and-size branch for a worked solution.

An alternative is to represent a signed number as the difference between two natural numbers. See the left-and-right branch for a worked solution.

The first representation is easier to understand, but the second is arguably easier to implement correctly.

About

Representing negative numbers in Ruby

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages