Last Updated: February 25, 2016
·
1.231K
· lccro

3 line recursive roman number converter

To use it simply call the to_roman method:

2.2.2 (main) > puts 2015.to_roman
MMXV

class Fixnum
  def to_roman
    Fixnum.roman(self)
  end

  private

  ROMAN_MAP = {
    1000 => 'M',
    900  => 'CM',
    500  => 'D',
    400  => 'CD',
    100  => 'C',
    90   => 'XC',
    50   => 'L',
    40   => 'XL',
    10   => 'X',
    9    => 'IX',
    5    => 'V',
    4    => 'IV',
    1    => 'I'
  }

  def self.roman(n)
    # recursion base
    return '' if n < 1
    # recursive step
    tuple = ROMAN_MAP.detect { |decimal, _roman| n >= decimal }
    tuple.last + (n - tuple.first).to_roman
  end
end

1 Response
Add your response

It relies on Hashes order being kept (ruby 1.9+) - https://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/

over 1 year ago ·