netbeans 和命令窗口中的 Ruby 字符编码问题
我使用 netbeans 作为开发 IDE 并从 cmd 运行应用程序,但在 cmd 窗口中以及从 netbeans 运行应用程序时无法正确显示 ISO 8859-1 字符,例如 åäö
问题: 最佳实践是什么 就是
现在我要做的
@output.puts indent + "V" + 132.chr + "lkommen till Ruby Camping!"
获取 ä
我的环境
>chcp 65001
Active code page: 65001
>ruby main.rb >
Source encoding: <Encoding:US-ASCII>
Default external: #<Encoding:UTF-8>
Default internal: nil
Locale charmap: "CP65001"
我在代码中的位置
def self.printEncoding
puts "Source encoding: #{__ENCODING__.inspect}" if defined? __ENCODING__
if defined? Environment::Encoding
puts "Default external: #{Encoding.default_external.inspect}"
puts "Default internal: #{Encoding.default_internal.inspect}"
puts "Locale charmap: #{ Encoding.locale_charmap.inspect}"
end
puts "LANG environment variable: #{ENV['LANG'].inspect}" unless ENV['LANG'].nil?
end
>ruby -v ruby 1.9.1p378(2010-01-10 修订版 26273)[i386-mingw32]
I use netbeans as development IDE and runs the application from cmd but have problems to display ISO 8859-1 characters like åäö correct in both cmd window and when I run the application from netbeans
Question: What is best practice to set it up
Right now I do
@output.puts indent + "V" + 132.chr + "lkommen till Ruby Camping!"
to get ä
My environment
>chcp 65001
Active code page: 65001
>ruby main.rb
Source encoding: <Encoding:US-ASCII>
Default external: #<Encoding:UTF-8>
Default internal: nil
Locale charmap: "CP65001"
where I have in the code
def self.printEncoding
puts "Source encoding: #{__ENCODING__.inspect}" if defined? __ENCODING__
if defined? Environment::Encoding
puts "Default external: #{Encoding.default_external.inspect}"
puts "Default internal: #{Encoding.default_internal.inspect}"
puts "Locale charmap: #{ Encoding.locale_charmap.inspect}"
end
puts "LANG environment variable: #{ENV['LANG'].inspect}" unless ENV['LANG'].nil?
end
>ruby -v
ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-mingw32]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要在源文件中使用非 ASCII 字符,则需要声明源文件的编码。源文件的第一行(或者第二行,如果你有 shebang 行)需要是一个注释行,它(大致)与正则表达式匹配
换句话说:注释行以一些内容开头,然后包含字符串
coding
后跟一个可选符号,后跟一个有效的编码名称,后跟一些其他内容。所以,如果你把它放在
你的文件的顶部,你应该没问题。 等编辑器兼容。
请注意,正则表达式被明确设计为与 Vim或 Emacs
总是让我困惑的一件事是,Ruby 并不总是自动对字符串进行转码。您必须自己对它们进行转码:
If you want to use non-ASCII characters in your source file, you need to declare the encoding of the source file. The very first line of the source file (or the second, if you have a shebang line) needs to be a comment line which (roughly) matches the regexp
In other words: a comment line which starts with some stuff, then contains the string
coding
followed by an optional symbol followed by a valid encoding name followed by some other stuff.So, if you put
at the top of your file, you should be okay. Note that the regexp is explicitly designed to be compatible with editors such as Vim:
Or Emacs:
One thing that always trips me up, is that Ruby does not always automatically transcode strings. You have to transcode them yourself: