Skip to content

Romanrb

Gregory McIntyre edited this page Nov 7, 2013 · 2 revisions
# roman.rb
#
# Return the string containing the roman numerals for the number provided.
#
# For more information:
#
#   http://en.wikipedia.org/wiki/Roman_numerals
#
def roman(number)
  # TODO: Make this deal with any number correctly.

  result = "" # start with an empty string
  while number >= 10 # convert 10s
    number -= 10
    result << "X" # << append a string onto an existing string
  end
  while number >= 5 # convert 5s
    number -= 5
    result << "V" # << append a string onto an existing string
  end
  return result
end

# ----------------------------------------------------------------------
# Run some tests to check to see if you're right.
#
# To run the file,
# - if you are using Sublime, press Ctrl+B
# - if you are using a command prompt, enter:
#
#    ruby roman.rb
#
# You will see output that tells you if you got it right:
#
# E means error, F means failure, . means correct.
#
# The tests are run in a random order each time.

require "minitest/spec"
require "minitest/autorun"

describe "roman" do
  [
    [1, "I"],
    [2, "II"],
    [3, "III"],
    [4, "IV"],
    [5, "V"],
    [10, "X"],
    [11, "XI"],
    [14, "XIV"],
    [20, "XX"],
  ].each do |input, expected|
    it "should convert the number #{input} to #{expected}" do
      roman(input).must_equal expected
    end
  end
end
Clone this wiki locally