西纳特拉 (Sinatra) 标题
我正在尝试在 Sinatra 中创建一个 slug 助手。这是代码(如此处所示):
helpers do
def sluggify(title)
accents = {
['á','à','â','ä','ã'] => 'a',
['Ã','Ä','Â','À'] => 'A',
['é','è','ê','ë'] => 'e',
['Ë','É','È','Ê'] => 'E',
['í','ì','î','ï'] => 'i',
['Î','Ì'] => 'I',
['ó','ò','ô','ö','õ'] => 'o',
['Õ','Ö','Ô','Ò','Ó'] => 'O',
['ú','ù','û','ü'] => 'u',
['Ú','Û','Ù','Ü'] => 'U',
['ç'] => 'c', ['Ç'] => 'C',
['ñ'] => 'n', ['Ñ'] => 'N'
}
accents.each do |ac,rep|
ac.each do |s|
title = title.gsub(s, rep)
end
end
title = title.gsub(/[^a-zA-Z0-9 ]/,"")
title = title.gsub(/[ ]+/," ")
title = title.gsub(/ /,"-")
title = title.downcase
end
end
我不断收到此错误:
private method `gsub' called for nil:NilClass
到底是什么出了问题吗?
I'm trying to create a slug helper in Sinatra. Here's the code (as seen here):
helpers do
def sluggify(title)
accents = {
['á','à','â','ä','ã'] => 'a',
['Ã','Ä','Â','À'] => 'A',
['é','è','ê','ë'] => 'e',
['Ë','É','È','Ê'] => 'E',
['í','ì','î','ï'] => 'i',
['Î','Ì'] => 'I',
['ó','ò','ô','ö','õ'] => 'o',
['Õ','Ö','Ô','Ò','Ó'] => 'O',
['ú','ù','û','ü'] => 'u',
['Ú','Û','Ù','Ü'] => 'U',
['ç'] => 'c', ['Ç'] => 'C',
['ñ'] => 'n', ['Ñ'] => 'N'
}
accents.each do |ac,rep|
ac.each do |s|
title = title.gsub(s, rep)
end
end
title = title.gsub(/[^a-zA-Z0-9 ]/,"")
title = title.gsub(/[ ]+/," ")
title = title.gsub(/ /,"-")
title = title.downcase
end
end
I keep getting this error:
private method `gsub' called for nil:NilClass
What exactly is going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“究竟出了什么问题?”
嗯,错误消息是不言自明的。您调用此方法时,标题变量设置为nil。要重现错误,请尝试调用:
我想它在这一行失败了:
为了避免这种情况,您可以在方法的开头检查 nil 标题:
或者(恕我直言,更优雅)始终转换标题到字符串,最终将 nil 转换为空字符串:
顺便说一句,您的代码可能需要进行一些认真的重构。首先,尝试替换:
或使用
tr 方法而不是gsub 用于字符到字符的替换:
"What exactly is going wrong?"
Well, the error message is kinda self-explanatory. You called this method with title variable set to nil. To reproduce the error, try calling:
I suppose that it failed on this line:
To avoid this, you can either check for nil title at the beginning of the method:
or (IMHO more elegant) always convert title to string, which converts eventual nil to empty string:
BTW your code could use some serious refactoring. For a start, try replacing:
with
or use tr method instead of gsub for character-to_character replacement:
我无法复制你所看到的。这是我的测试(在 Sinatra 之外,所以只使用一个模块):
Yields
testing-this
。I'm not able to duplicate what you're seeing. Here's my test (outside of Sinatra, so just using a module):
Yields
testing-this
.看看 iconv 的音译能力。它可以让您避免构建自己的字符转换表。
奥比·费尔南德斯来救援:http://www.jroller.com/obie/tags/unicode< /a>
Take a look at iconv's transliteration ability. It will let you avoid building your own table of character conversions.
Obie Fernandez to the rescue: http://www.jroller.com/obie/tags/unicode