8

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

Michael
  • 185
  • 1
  • 10
  • 2
    Note that "Extended ASCII" is an umbrella term, it doesn't refer to a specific character encoding. – Stefan Feb 24 '15 at 13:28
  • 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 Feb 24 '15 at 13:43
  • You should use Unicode/UTF-8 (unless you have to support legacy systems). See [Block Elements](http://en.wikipedia.org/wiki/Block_Elements) and [Box-drawing](http://en.wikipedia.org/wiki/Box_Drawing). – Stefan Feb 24 '15 at 13:47
  • 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 Feb 24 '15 at 13:58

4 Answers4

12

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 '█'
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • Thank You. This is exactly what I was looking for. Most of my programming experience for console applications was for DOS 6.0 and ASCII was still king. Programming in Windows I never had to worry about it. – Michael Feb 24 '15 at 14:08
4

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

219.chr(Encoding::UTF_8)
jam
  • 3,640
  • 5
  • 34
  • 50
  • 1
    You can also pass an encoding name, e.g. `219.chr('UTF-8')` – Stefan Feb 24 '15 at 13:30
  • What is the encoding for Extended_ASCII because UTF-8 does not have the same characters such as the solid block and borders that ASCII does. – Michael Feb 24 '15 at 13:32
  • 1
    "Extended ASCII" isn't an encoding, as such, so it's difficult to say exactly what your text is using (see http://en.wikipedia.org/wiki/Extended_ASCII) – jam Feb 24 '15 at 13:52
3

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')
# => "Û" 
shivam
  • 16,048
  • 3
  • 56
  • 71
0

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

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

more information in method doc.

rubycademy.com
  • 509
  • 5
  • 16