Display Extended-ASCII character in Ruby
Asked Answered
W

4

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

Woolgrower answered 24/2, 2015 at 12:42 Comment(4)
Note that "Extended ASCII" is an umbrella term, it doesn't refer to a specific character encoding.Asexual
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.Woolgrower
You should use Unicode/UTF-8 (unless you have to support legacy systems). See Block Elements and Box-drawing.Asexual
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.Woolgrower
A
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 '█'
Asexual answered 24/2, 2015 at 13:58 Comment(1)
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.Woolgrower
A
4

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

219.chr(Encoding::UTF_8)
Ankh answered 24/2, 2015 at 12:52 Comment(3)
You can also pass an encoding name, e.g. 219.chr('UTF-8')Asexual
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.Woolgrower
"Extended ASCII" isn't an encoding, as such, so it's difficult to say exactly what your text is using (see en.wikipedia.org/wiki/Extended_ASCII)Ankh
M
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')
# => "Û" 
Moist answered 24/2, 2015 at 12:55 Comment(0)
A
0

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

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

more information in method doc.

Arnoldarnoldo answered 24/2, 2015 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.