Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display an ascii art string in ruby?

Tags:

ruby

ascii

I'm trying to use an ascii art string that I made with artii in a ruby program. The string can be generated using the cli as expected:

enter image description here

However when I try to save it as a string and either puts, p, or print it, it doesn't work. I thought it might be because the slashes need to be escaped which I've tried to do, but it looks like I'm not gsubing correctly either. How would I go about going from a working string on the cli to a working string in a ruby program that's printing the string to stdout? enter image description here

banner = "
  _____       _             _   _       _       
 |  __ \     | |           | \ | |     | |      
 | |__) |   _| |__  _   _  |  \| | ___ | |_ ___ 
 |  _  / | | | '_ \| | | | | . ` |/ _ \| __/ _ \
 | | \ \ |_| | |_) | |_| | | |\  | (_) | |_  __/
 |_|  \_\__,_|_.__/ \__, | |_| \_|\___/ \__\___|
                     __/ |                      
                    |___/                       

"
print banner
print banner.gsub(/\\/, "\\\\")
puts "One slash: \\"
puts "Two slashes: \\\\"
like image 274
mbigras Avatar asked May 16 '16 23:05

mbigras


2 Answers

You can also use a heredoc that disables interpolation and escaping:

puts <<-'EOF'
 _____       _             _   _       _       
|  __ \     | |           | \ | |     | |      
| |__) |   _| |__  _   _  |  \| | ___ | |_ ___ 
|  _  / | | | '_ \| | | | | . ` |/ _ \| __/ _ \
| | \ \ |_| | |_) | |_| | | |\  | (_) | |_  __/
|_|  \_\__,_|_.__/ \__, | |_| \_|\___/ \__\___|
                    __/ |                      
                   |___/                       
EOF
like image 112
betabandido Avatar answered Oct 04 '22 18:10

betabandido


You can't gsub backslashes because they're not there: you're trying to unspill the milk. The syntax "foo\ bar" will produce the string "foo bar", exactly like if the backslash wasn't there. It's not that the backslash is not displaying - it is never in the string in the first place, so there is nothing to gsub. You have basically two solutions: either double the backslashes in your literal by hand or by editor replacement ("foo\\ bar") before your program executes:

artii 'Ruby Note' | sed 's/\\/\\\\/g'

or read the string in from somewhere so it is not interpreted by Ruby syntax:

banner = File.read(DATA)
puts banner
__END__
  _____       _             _   _       _       
 |  __ \     | |           | \ | |     | |      
 | |__) |   _| |__  _   _  |  \| | ___ | |_ ___ 
 |  _  / | | | '_ \| | | | | . ` |/ _ \| __/ _ \
 | | \ \ |_| | |_) | |_| | | |\  | (_) | |_  __/
 |_|  \_\__,_|_.__/ \__, | |_| \_|\___/ \__\___|
                     __/ |                      
                    |___/                       

will display what you want.

like image 35
Amadan Avatar answered Oct 04 '22 17:10

Amadan