red888 red888 - 3 months ago 5
Ruby Question

How to create array of strings with numbers prefixed with zeros? (derp01,derp02,derp03)

Is there a more ruby way I can do this (less lines and easy to read):

derpNum = 20
derpNames = Array.new
derpNum.times do |derp|
if derp < 10
derpNames << "derp0#{derp}"
else
derpNames << "derp#{derp}"
end
end

Answer
(1..20).map{|i| 'derp' + i.to_s.rjust(2, '0')}

or

(1..20).map{|i| 'derp%02d' % i}

%02d is a placeholder, which should be replaced with a 2-digit number, prefixed by 0 if it is not long enough.

Comments