本文介绍了Ruby将标题发布给Slug的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我应该如何在Ruby中将帖子标题转换为子弹?
How should I convert a post title to a slug in Ruby?
标题可以有任何字符,但我只希望子弹允许[a-z0-9-_]
(应该允许任何其他字符吗?).
The title can have any characters, but I only want the slug to allow [a-z0-9-_]
(Should it allow any other characters?).
所以基本上:
- 小写所有字母
- 将空格转换为连字符
- 删除无关字符
推荐答案
slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
downcase
使其变为小写. strip
确保没有前导或尾随空格.第一个gsub
用连字符替换空格.第二个gsub
删除所有非alpha非破折号非下划线字符(请注意,该集合与\W
非常接近,但也包括破折号,这就是为什么在此处说明的原因).
downcase
makes it lowercase. The strip
makes sure there is no leading or trailing whitespace. The first gsub
replaces spaces with hyphens. The second gsub
removes all non-alpha non-dash non-underscore characters (note that this set is very close to \W
but includes the dash as well, which is why it's spelled out here).
这篇关于Ruby将标题发布给Slug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!