Decimal to roman numeral converter in ruby

Ruby program for Decimal to roman numeral converter. Here mentioned other language solution.

#  Ruby program for
#  Conversion from Decimal to roman number

# Display roman value of n
def self.result( n)
    if (n==1)
        print("I")
    elsif(n==4)
        print("IV")
    elsif(n==5)
        print("V")
    elsif(n==9)
        print("IX")
    elsif(n==10)
        print("X")
    elsif(n==40)
        print("XL")
    elsif(n==50)
        print("L")
    elsif(n==90)
        print("XC")
    elsif(n==100)
        print("C")
    elsif(n==400)
        print("CD")
    elsif(n==500)
        print("D")
    elsif(n==900)
        print("DM")
    elsif(n==1000)
        print("M")
    end
end
def select( number,  collection,  size)
    n = 1
    i = 0
    i = 0
    while (i < size)
        if (number >= collection[i])
            n = collection[i]
        else
            break
        end
        i += 1
    end
    result(n)
    # Reduce the value of number
    return number - n
end
def romanNo( number)
    if (number <= 0)
        # When is not a natural number
        return
    end
    # Base case collection
    collection =
    [1, 4, 5, 9, 10, 40, 50, 90, 100, 
    400, 500, 900, 1000]
    # Get the size of collection
    size = collection.length
    print(" " + number.to_s + " : ")
    while (number > 0)
        number = select(number, 
            collection, size)
    end
    # Add new line
    print("\n")
end


# Test Case
romanNo(10)
romanNo(18)
romanNo(189)
romanNo(604)
romanNo(982)
romanNo(3000)

Output

 10 : X
 18 : XVIII
 189 : CLXXXIX
 604 : DCIV
 982 : DMLXXXII
 3000 : MMM



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved