有没有更多的红宝石方式我可以做到这一点(线条更少,易于阅读):
derpNum = 20
derpNames = Array.new
derpNum.times do |derp|
if derp < 10
derpNames << "derp0#{derp}"
else
derpNames << "derp#{derp}"
end
end
答案 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