简体   繁体   中英

Print Horizontal Line in Ruby

Can ruby's puts or print draw horizontal line kind of like bash does with printf+tr does ?

printf '%20s\n' | tr ' ' -

this will draw:

--------------------

You can use the following snippet

puts "-"*20

Check this for more help.

You might be interested in formatting using ljust , rjust and center as well.

I use a quick puts "*"*80 for debug purposes. I'm sure there are better ways.

For fancy lines:

p 'MY_LINE'.center(80,'_-')
#=> "_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-MY_LINE_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_"

You could also have the following:

puts "".center(20, "-")

irb(main):005:0> puts "".center(20, '-')
=> "--------------------"

This could be more flexible if you wanted to add additional information:

irb(main):007:0> puts "end of task".center(20, "-")
----end of task-----
=> nil

You can also use String#ljust or String#rjust .

puts ''.rjust(20,"-")
# >> --------------------
puts ''.ljust(20,"-")
# >> --------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM