20

Is there a Ruby function that can pad a string?

Original [477, 4770]

Expected ["477 ", "4770 "]

1
  • Can you provide an example code otherwise it's not really clear what you want? Commented Jun 23, 2015 at 7:25

4 Answers 4

30

You should use String#ljust from Ruby standard library:

arr = [477, 4770]
strings = arr.map { |number| number.to_s.ljust(5) }
# => ["477  ", "4770 "]
Sign up to request clarification or add additional context in comments.

1 Comment

Obviously use rjust(5) to add padding spaces to the left side of the string (at the risk of stating the obvious!) - apidock.com/ruby/String/rjust
13

You need the method String#ljust. Here is an example:

t = 123
s = t.to_s.ljust(5, ' ')

Please note that ' ' is the default padding symbol. I only added it for clarity.

Comments

2

You can use printf formatting from Kernel as well :

arr = [477, 4770]
arr.map { |i| "%-5d" % i }

Comments

2
arr = [477, 4770]

arr.collect {|num| num.to_s.ljust(5)}

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.