将 UTF-8 设置为 Ruby 1.9.3 的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20521371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set UTF-8 as default for Ruby 1.9.3
提问by Fellow Stranger
I'm on Rails 4 and Ruby 1.9.3
我在使用 Rails 4 和 Ruby 1.9.3
I use "strange" characters very often, so I have to declare UTF-8 encoding at the top of all .rb files.
我经常使用“奇怪”的字符,所以我必须在所有 .rb 文件的顶部声明 UTF-8 编码。
Is there any way to set UTF-8 as the default encoding for Ruby 1.9.3?
有没有办法将 UTF-8 设置为 Ruby 1.9.3 的默认编码?
I tried all answers, but when running rake db:seedand creating an object whose attributes contain non US-ASCIIvalid characters, I still receive this error:
我尝试了所有答案,但是在运行rake db:seed和创建属性包含US-ASCII无效字符的对象时,我仍然收到此错误:
`block in trace_on': invalid byte sequence in US-ASCII (ArgumentError)
回答by Holger Just
To change the source encoding (i.e. the encoding your actual written source code is in), you have to use the magic comment currently:
要更改源编码(即您实际编写的源代码所在的编码),您当前必须使用魔术注释:
# encoding: utf-8
It is not enough to either set the internal encoding (the encoding of the internal string representation after conversion) or the external encoding (the assumed encoding of read files). You actually have to set the magic encoding comment on top of files to set the source encoding.
设置内部编码(转换后内部字符串表示的编码)或外部编码(读取文件的假定编码)是不够的。您实际上必须在文件顶部设置魔术编码注释以设置源编码。
In ChiliProjectwe have a rake taskwhich sets the correct encoding header in all files automatically before a release.
在ChiliProject 中,我们有一个rake 任务,它在发布之前自动在所有文件中设置正确的编码头。
As for encoding defaults:
至于编码默认值:
- Ruby 1.8 and below didn't knew the concept of string encodings at all. Strings were more or less byte arrays.
- Ruby 1.9: default string encoding is
US_ASCIIeverywhere. - Ruby 2.0 and above: default string encoding is
UTF-8.
- Ruby 1.8 及以下版本根本不知道字符串编码的概念。字符串或多或少是字节数组。
- Ruby 1.9:默认字符串编码
US_ASCII无处不在。 - Ruby 2.0 及更高版本:默认字符串编码为
UTF-8.
Thus, if you use Ruby 2.0, you could skip the encoding comment and correctly assume UTF-8 encoding everywhere by default.
因此,如果您使用 Ruby 2.0,您可以跳过编码注释,并在默认情况下正确假定 UTF-8 编码。
回答by Sean Larkin
I think you would want one of the following, depending on the context.
我认为您需要以下其中一项,具体取决于上下文。
Encoding.default_internal = Encoding::UTF_8
Encoding.default_external = Encoding::UTF_8
This setting is made in the environment.rb file.
此设置在 environment.rb 文件中进行。
回答by Зелёный
in Ruby 1.9 the default is ASCII
in Ruby 2.0 the default is UTF-8.
在 Ruby 1.9 中默认是 ASCII
在 Ruby 2.0 中默认是 UTF-8。
change Ruby version
更改 Ruby 版本
or
或者
config.encoding = "utf-8" # application.rb
and
in your database.yml
并且在你的 database.yml
development:
adapter: your_db
host: localhost
encoding: utf8

