You can use the modula division % in combination with the String#%-method. (You don't need the format-command):
[1, 12, 123, 1234].map { |e| "%03d" % (e % 1000)}
With some marker to explain the different %:
[1, 12, 123, 1234].map { |e| "%03d" % (e % 1000)}
# (1) (2) (3)
- (1): format specification, 3 numerals with leading zero.
- (2):
String#%-method
- (3): Modula division for integers
In your comment in w0lf's answer you mention:
There is still this kind dependency/duplication between the format string and the divisor.
You can define the number of digits in a variable and use it in the format string and the divisor:
digits = 3
[1, 12, 123, 1234].map { |e| "%0*d" % [digits,e % 10**digits]}
[-3..-1]can be replaced with[/...$/]. I find the latter a bit easier to read, but I guess that's subjective.[-3..-1]is faster than using a regex.