Ruby-on-rails 简单的正则表达式——用空格替换下划线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1349916/
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
simple regex -- replace underscore with a space
提问by mportiz08
Hey, I'm writing my first Rails app, and I'm trying to replace the underscores form an incoming id name with spaces, like this:
嘿,我正在编写我的第一个 Rails 应用程序,我正在尝试用空格替换传入 id 名称中的下划线,如下所示:
before: test_string
之前:test_string
after: test string
之后:测试字符串
How can I do this? Sorry if this is a bit of a dumb question, I'm not very familiar with regular expressions...
我怎样才能做到这一点?对不起,如果这是一个愚蠢的问题,我对正则表达式不是很熟悉......
采纳答案by mportiz08
Whoops, I actually had it working--just forgot to update the variable name :P
哎呀,我实际上让它工作了——只是忘了更新变量名:P
I was using this:
我正在使用这个:
@id = params[:id]
@title = @id.gsub("_", " ")
回答by Jeremy Ruten
str.gsub!(/_/, ' ')
gsubstands for 'global substitution', and the exclamation means it'll change the string itself rather than just return the substituted string.
gsub代表“全局替换”,感叹号意味着它会改变字符串本身,而不是仅仅返回被替换的字符串。
You can also do it without regexes using String#tr!:
您也可以在没有正则表达式的情况下使用String#tr!:
str.tr!('_', ' ')
回答by Andión
On rails you can use the simplier .humanizeand ruby's .downcasemethod but be careful as it also strips any final '_id' string (in most cases this is just what you need, even the capitalized first letter)
在 rails 上,您可以使用更简单.humanize和 ruby 的.downcase方法,但要小心,因为它还会删除任何最终的 '_id' 字符串(在大多数情况下,这正是您所需要的,即使是大写的第一个字母)
'text_string_id'.humanize.downcase
=> "text string"
回答by Suganya
Using split and join in rails
在 rails 中使用 split 和 join
"test_string".split('_').join(' ')
"test_string".split('_').join('')

