1

My goal is to create a one line output with 3 different variables (all strings) that is formatted with the first variable being left aligned, the 2nd variable being centered, and the last variable being right aligned with spaces padding the variables if their size is less than the space allotted.

The variable slots are: variables 1,3 = max string length of 10 variable 2 = max string length of 7 (there will be space buffers of 2 spaces between variables 1&2 and 2&3)

I would like variables 1&3 to be the same size (10) regardless of user input. If the input is less than 10, I want there to either being padding at the end (variable 1 - left aligned) or at the beginning (variable 3 - right aligned).

I've tried using/learning the sprintf methods with various formats and arguments but I keep getting errors or blank outputs all together.

****IDEAL OUTPUT EXAMPLE****

VARIABLE 1  VARIAB2  VARIABLE 3
1
  • 1
    What have you tried? Can you post the snippets of code that you've attempted that haven't quite worked? Commented Dec 16, 2017 at 20:59

1 Answer 1

2

You can use the various methods available in the String class.

input1 = 'one'
input2 = 'two'
input3 = 'three'

input1 = input1.ljust 10
 #=> "one       "
input2 = input2.center 7     #credit to user Simple Lime
 #=> "  two  "
input3 = input3.rjust 10
 #=> "     three"

puts output = input1 + '  ' + input2 + '  ' + input3
 #one           two         three
output.size
 #=> 31
Sign up to request clarification or add additional context in comments.

2 Comments

@SimpleLime I see what you mean about the loop. Also I can't believe I missed center. Thanks, have updated my answer.
This is what I needed. Didn't realize there was a built-in method already in Ruby. Thank you for your help, this is perfect.

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.