Reputation: 8055
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:
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?
banner = "
_____ _ _ _ _
| __ \ | | | \ | | | |
| |__) | _| |__ _ _ | \| | ___ | |_ ___
| _ / | | | '_ \| | | | | . ` |/ _ \| __/ _ \
| | \ \ |_| | |_) | |_| | | |\ | (_) | |_ __/
|_| \_\__,_|_.__/ \__, | |_| \_|\___/ \__\___|
__/ |
|___/
"
print banner
print banner.gsub(/\\/, "\\\\")
puts "One slash: \\"
puts "Two slashes: \\\\"
Upvotes: 6
Views: 5435
Reputation: 19704
You can also use a heredoc that disables interpolation and escaping:
puts <<-'EOF'
_____ _ _ _ _
| __ \ | | | \ | | | |
| |__) | _| |__ _ _ | \| | ___ | |_ ___
| _ / | | | '_ \| | | | | . ` |/ _ \| __/ _ \
| | \ \ |_| | |_) | |_| | | |\ | (_) | |_ __/
|_| \_\__,_|_.__/ \__, | |_| \_|\___/ \__\___|
__/ |
|___/
EOF
Upvotes: 9
Reputation: 198324
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.
Upvotes: 4