Roman numeral converter in Ruby For a Project Euler problem, I made a Ruby roman numeral converter:

def romanize(num)
    digits = {
        1000 =&gt; "M",
        900  =&gt; "CM", 500 =&gt; "D", 400 =&gt; "CD", 100 =&gt; "C",
        90   =&gt; "XC", 50  =&gt; "L", 40  =&gt; "XL", 10  =&gt; "X",
        9    =&gt; "IX", 5   =&gt; "V", 4   =&gt; "IV", 1   =&gt; "I"
    }
    digits.reduce("") do |acc, digit|
        key, numeral = digit
        occurances, num = num.divmod(key)
        acc + (numeral * occurances)
    end
end


This works great, but I'm not sure it's good Ruby. Specifically, I'm wondering if the body of the reduce block could be shortened, and if it could made more clear.

For example, I don't think its that obvious that num is being modified in the middle of the reduce block.

Also, I know I can monkey patch this into the Fixnum class, but that's not what I'm looking for.

Update #1

@Tokland's answer taught me some new things. His answer works well, and is pretty clever.

If I take just two of his concepts and apply them to mine, the digits.reduce("") ... block can be simplified to:

digits.map do |key, numeral|
    occurances, num = num.divmod(key)
    numeral * occurances
end.join


This needs one less line because it deconstructs the digit key/value in the block arguments. Also, it creates an array which is joined into a string at the end. For big numbers (around 100-trillion), this is much quicker.

The only problem I still see is that it's modifying the num variable, which is essentially global state to the block.
Some notes:


Use 2 spaces for indentation, not 4.
key, numeral = digit: You can unpack block arguments: do |acc, (key, numeral)|.
Concating strings is costly, better build an array and finally join it.
You are using inject, which is great because it'a functional abstraction, but you are modifying num on each iteration, so it ends up being a weird mixture of functional and imperative style. I know it's a bit cumbersome, but conceptually it's better to keep also num in the accumulator.


I'd write:

digits.reduce(:output =&gt; [], :num =&gt; num) do |state, (key, numeral)|
  ocurrences, remainder = state[:num].divmod(key)
  {:output =&gt; state[:output] &lt;&lt; (numeral * ocurrences), :num =&gt; remainder} 
end[:output].join