Reputation: 185
How can I print an Extended-ASCII character to the console. For instance if I use the following
puts 57.chr
It will print "9" to the console. If I were to use
puts 219.chr
It will only display a "?". It does this for all of the Extended-ASCII codes from 128 to 254. Is there a way to display the proper character instead of a "?".
Upvotes: 8
Views: 4131
Reputation: 114138
I am trying to using the drawing characters to create graphics in my console program.
You should use UTF-8 nowadays.
Here's an example using characters from the Box Drawing Unicode block:
puts "╔═══════╗\n║ Hello ║\n╚═══════╝"
Output:
╔═══════╗
║ Hello ║
╚═══════╝
So if for instance I was going to use the Unicode character U+2588 (the full block) how would I print that to the console in Ruby.
You can use:
puts "\u2588"
or:
puts 0x2588.chr('UTF-8')
or simply:
puts '█'
Upvotes: 12
Reputation: 529
You can use the method Integer#chr([encoding])
:
219.chr(Encoding::UTF_8) #=> "Û"
more information in method doc.
Upvotes: 0
Reputation: 16506
You need to specify the encoding of the string and then convert it to UTF-8
. For example if I want to use Windows-1251 encoding:
219.chr.force_encoding('windows-1251').encode('utf-8')
# => "Ы"
Similarly for ISO_8859_1
:
219.chr.force_encoding("iso-8859-1").encode('utf-8')
# => "Û"
Upvotes: 3