如何使用带有前缀为零的数字创建字符串数组? (derp01,derp02,derp03)

时间:2016-08-17 04:48:08

标签: ruby

有没有更多的红宝石方式我可以做到这一点(线条更少,易于阅读):

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

3 个答案:

答案 0 :(得分:5)

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

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

%02d是占位符,如果不够长,则应使用2位数字替换,前缀为0

答案 1 :(得分:2)

你可以试试这个:

(1..20).map { |i| i > 9 ? i.to_s : "0#{i}" }

答案 2 :(得分:0)

这个怎么样?

collection    = []
collection[0] = 'derp01'

19.times {|index| collection.push(collection.last.next)}

# Output
 => collection
 => ["derp01", "derp02", "derp03", "derp04", "derp05", "derp06", "derp07", "derp08", "derp09", "derp10", "derp11", "derp12", "derp13", "derp14", "derp15", "derp16", "derp17", "derp18", "derp19", "derp20"]

请参阅next模块

中的Enumerable this link