はじめに
今回は以下の記事にある,アラビア数字を受け取って,ローマ数字を返す関数to_romanをrubyで実装する.
roman numerals
境界値が沢山あってifだらけになってしまうような場合は,配列に境界値を入れてループで回すという実装テクニックが使える場合がある.今回はこの方法が有効なので使う.
roman_numerals.rb
def to_roman(n)
raise RangeError if n <= 0 or 4000 <= n
arabic_num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
roman_num = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
ret = ""
arabic_num.zip(roman_num) do |arabic, roman|
while n >= arabic do
n -= arabic
ret << roman
end
end
return ret
end
発展課題
この関数をIntegerクラスのメソッドとして追加してみる.
roman_numerals.rb
class Integer
def to_roman
n = self
raise RangeError if n <= 0 or 4000 <= n
arabic_num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
roman_num = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
ret = ""
arabic_num.zip(roman_num) do |arabic, roman|
while n >= arabic do
n -= arabic
ret << roman
end
end
return ret
end
end
すると以下のように使える.
roman_numerals.rb
3999.to_roman # => "MMMCMXCIX"
- source ~/grad_members_20f/members/ryuta-kikuchi/qiita_articles/roman_numerals.org