我在代碼中添加了一些補充,希望現在清楚。 雖然你永遠不會這樣寫,你發佈的代碼很好。
class Integer
def to_roman_explained
roman_arr = {
1000 => "M",
900 => "CM",
500 => "D",
400 => "CD",
100 => "C",
90 => "XC",
50 => "L",
40 => "XL",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I"
}
remaining = self # the integer on which this method is called
empty_string = "" # startvalue of result
return_value = roman_arr.inject(empty_string) do |result, (arab, roman)|
# inject = reduce, for each element of our hash
# arab and roman are the key and value part of the hash elements, result is result from previous iteration
p [result, arab, roman,remaining.divmod(arab)] # lets's see what happens
# number of times the remaining can be divided with the value of this roman, the remaining becomes the rest
whole_part, remaining = remaining.divmod(arab)
result << roman * whole_part # if whole_part == 0 nothing happens for this roman
end
return return_value
end
end
puts 555.to_roman_explained
# gives
# ["", 1000, "M", [0, 555]]
# ["", 900, "CM", [0, 555]]
# ["", 500, "D", [1, 55]] first time the integer is dividable by the value of the roman
# ["D", 400, "CD", [0, 55]] our result now has the roman D
# ["D", 100, "C", [0, 55]]
# ["D", 90, "XC", [0, 55]]
# ["D", 50, "L", [1, 5]] etc
# ["DL", 40, "XL", [0, 5]]
# ["DL", 10, "X", [0, 5]]
# ["DL", 9, "IX", [0, 5]]
# ["DL", 5, "V", [1, 0]] etc
# ["DLV", 4, "IV", [0, 0]]
# ["DLV", 1, "I", [0, 0]]
# DLV
嘗試把一些調試打印的循環。另外,你在找到這個之前是否實現了自己的解決方案?如果你認真思考並做到了這一點,那麼這將是有道理的。 – 2014-09-29 04:28:57
順便說一句,嘗試讀這篇文章:http://tech.tulentsev.com/2014/02/kata-convert-numbers-to-roman-numerals/。循環部分是不同的,但有更多的解釋。 :) – 2014-09-29 04:32:37