1

I have an array of values and I would like to print it in some format. In C# I would do

string.Format(" {0} | {1} _ {2}!", array[0], array[1], array[2]);

resulting in an output such as

" 10 | 20 _ 30!"

How to achieve this in Ruby?

2 Answers 2

4

Is this what you are looking for using String#% ?

array=[11,13,14]
" %s | %s _ %s!" % [array[0],array[1],array[2]]
# => " 11 | 13 _ 14!"
array=[0,13,14]
" %s | %s _ %s!" % array
# => " 0 | 13 _ 14!"
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, also works. Is there a way how to effortlessly print space character when there is a value 0 in the array?
@OndrejJanacek I didn't catch you
Imagine that array[0] stores a value of 0 and I would like to see " | 13 _ 14" instead of " 0 | 13 _ 14"
I accepted your answer because you provided that solution with [*array] which is indeed nice.
@OndrejJanacek [*array] is redundant. It unpacks the array into... another array. Just do % array
|
1

In Ruby it should be

" #{array[0]} | #{array[1]} _ #{array[2]}!"

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.