[RUBY] roman numerals

ruby-2.7.1p83

Problem statement

Write a method that takes arabic numerals and returns roman numerals. https://qiita.com/daddygongon/items/2d0a73a51ddab2d9da1b

Solution (only halfway done)

First, simply output 1 to 5.

def to_roman(arabic)
  if arabic == 1
    p "I"
  elsif arabic == 2
    p "II"
  elsif arabic == 3
    p "III"
  elsif arabic == 4
    p "IV"
  elsif arabic == 5
    p "V"
  else
    p "false"
  end
end

if $PROGRAM_NAME == __FILE__
  arabic = ARGV[0].to_i
  to_roman(arabic)
end

This succeeds.

Next, it transforms into a shape using a loop.

def to_roman(arabic_numerals)
  arabic_and_roman = [[1,"I"], [2,"II"], [3,"III"], [4,"IV"], [5,"V"]]

  arabic_and_roman.each do |arabic, roman|
    if arabic_numerals == arabic
      return roman      
    end
  end
  puts(false)
end

This was also successful. If there is no number other than 1 to 5 or any input, it will be false.

Although there is a lot of manual work, I decided to arrange the numbers of the points where the notation changes in the arabic \ _and \ _roman variable.

At this point, the numbers that are not shown will be false, so I tried to make a conditional branch with if, but I couldn't solve it until the end.

def to_roman(arabic_numerals)
  arabic_and_roman = [[1,"I"], [4,"IV"], [5,"V"], [9,"IV"], [10,"X"], [40,"XL"], [50,"L"], [90,"XC"], [100,"C"], [400,"CD"], [500,"D"], [900,"CM"], [1000,"M"]]

  arabic_and_roman.each do |arabic, roman|
    if arabic_numerals == arabic
      return roman      
    end
  end
  puts(false)
end

if $PROGRAM_NAME == __FILE__
  arabic_numerals = ARGV[0].to_i
  puts(to_roman(arabic_numerals))
end

Recommended Posts

roman numerals
roman numerals
roman numerals
roman numerals
roman numerals
roman numerals
Roman Numerals
roman numerals
roman numerals
EX1: roman numerals
Let's solve the roman numerals
Find Roman numerals in Ruby
roman numerals (I tried to simplify it with hash)