Skip to content

Instantly share code, notes, and snippets.

@tachyons
Created April 17, 2016 08:13
Show Gist options
  • Save tachyons/a0128c4eafd55118f5977e354946644b to your computer and use it in GitHub Desktop.
Save tachyons/a0128c4eafd55118f5977e354946644b to your computer and use it in GitHub Desktop.
Roman Numerals Manage
class Fixnum
VERSION=1
ROMAN_SYMBOL_MAPPING= {
1=> "I",
5=> "V",
10=>"X",
50=>"L",
100=>"C",
500=>"D",
1000=>"M"
}
SUBTRACTABLE_SYMBOLS = {
'V'=>'I',
'X'=>'I',
'L'=>'X',
'C'=>'X',
'D'=>'C',
'M'=>'C'
}
def to_roman
return "M"*(self/1000)+(self%1000).to_roman if self > 1000
return "" if self==0
return ROMAN_SYMBOL_MAPPING[self] if ROMAN_SYMBOL_MAPPING.keys.include? self
diff=first_of_next_range-ROMAN_SYMBOL_MAPPING.invert[subtractable_symbol]
if diff < self
return (diff).to_roman + (self-diff).to_roman
elsif diff == self
return subtractable_symbol+ROMAN_SYMBOL_MAPPING[first_of_next_range]
else
return range.first.to_roman+(self-range.first).to_roman
end
end
private
def first_of_next_range
range.last+1
end
def subtractable_symbol
SUBTRACTABLE_SYMBOLS[ROMAN_SYMBOL_MAPPING[range.last+1]]
end
def range
self.class.ranges.select do |range| range.include? self%1000 end.first
end
def self.ranges
ranges=[]
6.times do | index|
ranges << (ROMAN_SYMBOL_MAPPING.keys[index]..ROMAN_SYMBOL_MAPPING.keys[index+1]-1)
end
ranges
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment