简体   繁体   English

Ruby 1.9 - 无效的多字节字符(US-ASCII)

[英]Ruby 1.9 - invalid multibyte char (US-ASCII)

Im trying to make my rails application (2.3.5) to run on Ruby 1.9, I've this function that make some transformations on a string: 我试图让我的rails应用程序(2.3.5)在Ruby 1.9上运行,我有这个函数在字符串上进行一些转换:

def replace_special_chars(downcase = true)
if downcase 
  string = self.downcase
else
  string = self
end
string.gsub! /á|ã|à|ä|â/, 'a'
string.gsub! /é|è|ë|ê/, 'e'
string.gsub! /í|ì|ï|î/, 'i'
string.gsub! /ó|õ|ò|ô|ö/, 'o'
string.gsub! /ú|ù|ü|û/, 'u'
string.gsub! /ç/, 'c'
string.gsub! /&/, 'e'
string.gsub! /\s/, '-'
string.gsub! /[^a-zA-Z_0-9-]/, ''
string.gsub! /-(-)+/, '-'
string
end

But when I try to start the server, I got this error: 但是当我尝试启动服务器时,我收到了这个错误:

<internal:lib/rubygems/custom_require>:29:in `require':   
/Users/.../lib/nzn_string.rb:11: invalid multibyte char (US-ASCII) (SyntaxError)
/Users/.../lib/nzn_string.rb:11: invalid multibyte char (US-ASCII) 
/Users/.../lib/nzn_string.rb:11: syntax error, unexpected $end, expecting keyword_end
string.gsub! /á|ã|à|ä|â/, 'a'
                ^

from :29:in `require' 来自:29:在`require'

What's the right way to do this on ruby 1.9? 在ruby 1.9上执行此操作的正确方法是什么? I don't know what im missing here 我不知道我在这里失踪了什么

Write # encoding: utf-8 on top of that file. 在该文件的顶部写# encoding: utf-8 That changes the default encoding of all string/regexp literals in that file utf-8 . 这会更改该文件utf-8中所有string / regexp文字的默认编码。 The default encoding for all literals is US-ASCII , which cannot represent á . 所有文字的默认编码是US-ASCII ,不能代表á

要在项目范围内进行,请尝试: magic_encoding gem。

I think you can also change the regexps from the syntax /re/ to the syntax (Regexp.new 're', nil, 'n') 我想你也可以将regexps从语法/ re /更改为语法(Regexp.new're',nil,'n')

For example, the instruction you mentioned: 例如,您提到的说明:

string.gsub! string.gsub! /á|ã|à|ä|â/, 'a' /á|ã|à|ä|â/,'a'

will become: 会变成:

string.gsub! string.gsub! (Regexp.new 'á|ã|à|ä|â', nil, 'n'), 'a' (Regexp.new'á|ã|à|ä|â',nil,'n'),'a'

More details here: 更多细节在这里:

http://www.ruby-forum.com/topic/183413 http://www.ruby-forum.com/topic/183413

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM