2

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:

--------------------
Tux
  • 247
  • 2
  • 14

5 Answers5

7

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.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • 1
    Just asking, doesn't ruby have something like `"{0:^20}".format(var)` like in Python? – Games Brainiac Nov 12 '13 at 16:54
  • @GamesBrainiac The output of the snippet you mention is `' - '` which is not what the OP needs. But `print("-" * 20)` should work in python as well. – Anshul Goyal Nov 12 '13 at 17:00
  • I realize that, but if you ask something a little more specific, then you you are broke. For example, if you wanted to fill up empty spaces with `-` and you have some string to format it with, then you're stuck. In python, its easy as `"{0:-^20}".format("END OF TASK")`. – Games Brainiac Nov 12 '13 at 17:02
  • 3
    @GamesBrainiac in ruby you can do this by `"END OF TASK".ljust(20,"-")` or `rjust` depending on the side you want to fill – Yevgeniy Anfilofyev Nov 12 '13 at 17:21
3

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

MegaTux
  • 1,591
  • 21
  • 26
1

For fancy lines:

p 'MY_LINE'.center(80,'_-')
#=> "_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-MY_LINE_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_"
hirolau
  • 13,451
  • 8
  • 35
  • 47
1

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
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • +1 Was about to reply with the same in comments to my answer, but then saw your answer. FWIW, the link in my answer has documentation for `.center`, `.ljust` and `.rjust` as well. – Anshul Goyal Nov 12 '13 at 17:35
  • 1
    @ansh0l I researched and found it out. I got a terrible bashing from the chat room guys though :P – Games Brainiac Nov 12 '13 at 17:35
0

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

puts ''.rjust(20,"-")
# >> --------------------
puts ''.ljust(20,"-")
# >> --------------------
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317