7
votes

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 "?".

4
Note that "Extended ASCII" is an umbrella term, it doesn't refer to a specific character encoding. - Stefan
I am trying to using the drawing characters to create graphics in my console program. I can't use anything like curses. ASCII Code 219 is a solid block. - Michael
You should use Unicode/UTF-8 (unless you have to support legacy systems). See Block Elements and Box-drawing. - Stefan
So if for instance, if I was going to use the Unicode character U+2588 (the full block) how would I print that to the console in Ruby. - Michael

4 Answers

11
votes

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 '█'
4
votes

You may need to specify the encoding, e.g.:

219.chr(Encoding::UTF_8)
3
votes

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')
# => "Û" 
0
votes

You can use the method Integer#chr([encoding]):

219.chr(Encoding::UTF_8)   #=> "Û"

more information in method doc.