2

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.

1
  • 1
    Questions about refactoring or the best way to write something, should be asked on Code Review. Commented Mar 10, 2014 at 16:20

2 Answers 2

5

What about using String#%?

(0..12).map { |i| "rate_limit_%03d" % i }
# => ["rate_limit_000", "rate_limit_001", "rate_limit_002", ...
Sign up to request clarification or add additional context in comments.

Comments

4

You can do this, using String#rjust method:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.