Skip to content

Instantly share code, notes, and snippets.

@szalansky
Created April 10, 2013 06:32
Show Gist options
  • Save szalansky/5352281 to your computer and use it in GitHub Desktop.
Save szalansky/5352281 to your computer and use it in GitHub Desktop.
Roman numbers calculator (did as kata with Ruby and RSpec).
require "rspec"
CONVERSIONS_FACTOR = [
[100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]
]
def conversion_factors_for number
CONVERSIONS_FACTOR.find { |arabic, _| arabic <= number }
end
def convert number
return "" if number.zero?
arabic, roman = conversion_factors_for number
roman + convert(number - arabic)
end
describe "Converting arabic numbers to roman numbers" do
context "Romans didn't have a 0" do
it "converts 0 to a blank string" do
expect(convert(0)).to eq("")
end
end
{
1 => "I",
2 => "II",
4 => "IV",
5 => "V",
6 => "VI",
10 => "X",
16 => "XVI",
20 => "XX",
40 => "XL",
50 => "L",
100 => "C",
90 => "XC"
}.each_pair do |arabic, roman|
it "converts #{arabic} to #{roman}" do
expect(convert(arabic)).to eq(roman)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment