I am trying to create a CLI application and I want to output text to the console. I cannot figure out how to format how I want.
When you type rails new app
, you get this output:
create tmp/cache
create tmp/cache/assets
create vendor/assets/javascripts
create vendor/assets/javascripts/.keep
create vendor/assets/stylesheets
create vendor/assets/stylesheets/.keep
run bundle install
How can I write my output to make sure all the commands are vertically aligned like that?
PS. I am using Thor is that matters.
Thanks
I think you're overthinking this. They are just printing out lines of text with spacing in between.
puts " create tmp/cache"
puts " create tmp/cache/assets"
# ...
will output exactly the same way.
There is a function in Ruby that would help out with this a tiny bit (String#rjust
), which will pad the string with spaces on the left. So if you want your first column to be 10 characters wide, you can rjust
the strings with a value of 10 and it will align them to the right. If you're iterating through a hash, for example, you might run the following code:
hash = { "hello" => "world", "foo" => "bar" }
hash.each do |key, value|
puts "#{key.rjust(7)} #{value}"
end
# hello world
# foo bar