Tux
Tux

Reputation: 247

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:

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

Upvotes: 2

Views: 1782

Answers (5)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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

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

Upvotes: 0

Anshul Goyal
Anshul Goyal

Reputation: 76887

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.

Upvotes: 7

Nafiul Islam
Nafiul Islam

Reputation: 82470

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

Upvotes: 1

hirolau
hirolau

Reputation: 13901

For fancy lines:

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

Upvotes: 1

MegaTux
MegaTux

Reputation: 1651

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

Upvotes: 3

Related Questions