在 Ruby 中显示扩展 ASCII 字符

Display Extended-ASCII character in Ruby

如何将扩展 ASCII 字符打印到控制台。例如,如果我使用以下

puts 57.chr

它将向控制台打印“9”。如果我要使用

puts 219.chr

它只会显示一个“?”。它对从 128 到 254 的所有扩展 ASCII 代码执行此操作。有没有办法显示正确的字符而不是“?”。

您可能需要指定编码,例如:

219.chr(Encoding::UTF_8)

您需要指定字符串的编码,然后将其转换为UTF-8。例如,如果我想使用 Windows-1251 编码:

219.chr.force_encoding('windows-1251').encode('utf-8')
# => "Ы"

ISO_8859_1 类似:

219.chr.force_encoding("iso-8859-1").encode('utf-8')
# => "Û" 

您可以使用方法 Integer#chr([encoding]):

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

更多信息见method doc

I am trying to using the drawing characters to create graphics in my console program.

现在你应该使用 UTF-8。

这是一个使用 Box Drawing Unicode 块中的字符的示例:

puts "╔═══════╗\n║ Hello ║\n╚═══════╝"

输出:

╔═══════╗
║ 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.

您可以使用:

puts "\u2588"

或:

puts 0x2588.chr('UTF-8')

或简单地:

puts '█'