我遇到了将特殊字符(或西班牙语的重音)标准化的问题。我创建了一个GEM作为学习练习(关于如何创建,安装和使用个人宝石),但不幸的是,每当我在另一个ruby文件上加载gem时,我就会遇到标题上的错误。下面的代码显示了我的GEM的构成(我知道代码非常糟糕,但这又是一次学习练习)。
#!/bin/env ruby
# encoding: utf-8
module SpanishStringNormalizer
class Normalizer
def self.spanishNormalize (aString)
while (aString.include? "á") ==true ||
(aString.include? "é") ==true ||
(aString.include? "í") ==true ||
(aString.include? "ó") ==true ||
(aString.include? "ú") ==true do
aString ["á"]= "a" if aString.include? "á"
aString ["é"]= "e" if aString.include? "é"
aString ["í"]= "i" if aString.include? "í"
aString ["ó"]= "o" if aString.include? "ó"
aString ["ú"]= "u" if aString.include? "ú"
end #end of while
return aString
end #end of spanishNormalize
end #end of class
end #end of module
然而,当我在另一个ruby文件上加载这个gem时,我收到以下错误
/Users/Andre/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `require':/Users/Andre/.rvm/gems/ruby-1.9.3-p429/gems/Spanish String Normalizer-0.0.0 / lib / spanish_str_normalizer.rb:25:语法错误, 意外'\ n',期待tCOLON2或'['或'。' (的SyntaxError)
我一直在尝试不同的事情,但我无法解决它。有人可以帮我确定我在做什么错误吗?
我的GEM项目可在此处找到:https://github.com/betogess506/Spanish-String-Normalizer
答案 0 :(得分:4)
我已经尝试过你的代码,但是我无法在我的系统上重现错误(无论是使用Ruby 2.0.0还是1.9.3)。但是我认为不值得烦恼自己解决这个问题,因为你的代码只能用String#tr
方法编写:
module SpanishStringNormalizer
def self.normalize(string)
string.tr('áéíóú', 'aeiou')
end
end
SpanishStringNormalizer.normalize('fóó')
# => "foo"
答案 1 :(得分:0)
正如@sawa所说,你的代码闻起来。臭气味。以下是你如何写它:
#!/bin/env ruby
# encoding: utf-8
module SpanishStringNormalizer
REPLACEMENTS = {
"á" => "a",
"é" => "e",
"í" => "i",
"ó" => "o",
"ú" => "u"
}
class Normalizer
def self.spanishNormalize (aString)
regex = Regexp.union(REPLACEMENTS.keys)
aString.gsub(regex, REPLACEMENTS)
end
end
end
至于你原来的问题,错误不在你的宝石中。我下载并要求它,并且要求工作正常。