Shpigford
Shpigford

Reputation: 25348

Creating this array programmatically?

I'm currently populating a simple array like so:

queues = %w(rate_limit_000 rate_limit_001 rate_limit_002 rate_limit_003 rate_limit_004 rate_limit_005 rate_limit_006 rate_limit_007 rate_limit_008 rate_limit_009 rate_limit_010 rate_limit_011 rate_limit_012)

That's ripe for refactoring. So what's the easiest way to build that array without manually adding items?

The only difference between the item names are those last 3 digits, which should always be 3 digits, but I do need to set a limit on how high it goes.

Upvotes: 2

Views: 65

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51151

You can do this, using String#rjust method:

(0..12).map do |i|
  "rate_limit_#{i.to_s.rjust(3, '0')}"
end

Upvotes: 4

toro2k
toro2k

Reputation: 19228

What about using String#%?

(0..12).map { |i| "rate_limit_%03d" % i }
# => ["rate_limit_000", "rate_limit_001", "rate_limit_002", ...

Upvotes: 5

Related Questions