在 Ruby on Rails 中,'#encoding: utf-8' 和 'config.encoding = "utf-8"' 是否不同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7699018/
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
In Ruby on Rails, are '#encoding: utf-8' and 'config.encoding = "utf-8"' different?
提问by Lai Yu-Hsuan
I can specify any ruby file to use specific encoding by add a comment line at its top:
我可以通过在其顶部添加注释行来指定任何 ruby 文件以使用特定编码:
#encoding: utf-8
But in Rails' config/application.rb, I found this:
但是在 Rails' 中config/application.rb,我发现了这个:
config.encoding = "utf-8"
Are they different? If I have set config.encoding = "utf-8", still I need #encoding: utf-8?
它们不同吗?如果我已经设置了config.encoding = "utf-8",我还需要#encoding: utf-8吗?
回答by Frost
The config.encoding = "utf-8"part in config/application.rbis related to how rails should interpret content.
中的config.encoding = "utf-8"部分config/application.rb与 rails 应该如何解释内容有关。
#encoding: utf-8in a ruby file tells ruby that this file contains non-ascii characters.
#encoding: utf-8在 ruby 文件中告诉 ruby 这个文件包含非 ascii 字符。
These two cases are different. The first one (in config/application.rb) tells rails something, and has nothing at all to do with how ruby itself should interpret source files.
这两种情况是不同的。第一个 (in config/application.rb) 告诉 rails 一些事情,与 ruby 本身应该如何解释源文件完全没有关系。
You can set the environment variable RUBYOPT=-Kuif you're lazy and want ruby to automatically set the default file encoding of .rbfiles to utf-8, but I'd rather recommend that you put your non-ascii bits in a translation file and reference that with I18n.t.
您可以设置环境变量RUBYOPT=-Ku,如果你是懒惰的,并希望红宝石自动设置的默认文件编码.rb文件utf-8,但我宁愿建议你把你的非ASCII位在翻译文件引用该I18n.t。

