Class: Integer

Inherits:
Object
  • Object
show all
Defined in:
lib/hack01/roman_numerals.rb

Constant Summary collapse

ROMANS =

what we are doing below is extending the class by adding a new method. to see the built in methods for class of integer type something like ‘5.methods.sort`

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

Instance Method Summary collapse

Instance Method Details

#to_romanObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/hack01/roman_numerals.rb', line 24

def to_roman
  number = self
  #  self is like `this` in javascript. in this example if we call this method thusly `5.to_roman` then self is 5
  output = ""

  # long way. would need lots of if / else statements.
  # if number == 1
  #   output = "I"
  # elsif number == 2
  #   output = "II"
  # else
  #   output = "III"
  # end

  # clever ruby way - eaching through the hash defined above.
  ROMANS.each do |key, value|
    # output = output + key * ( number / value )
    output << key * ( number / value )
    number = number % value
  end


  output
end