如何安全地用rubyreplace所有的下划线空格?
这适用于任何有空格的string
str.downcase.tr!(" ", "_") 但没有空格的string会被删除
所以“新学校”会变成“新学校”,但“色彩”会变成“”,什么都不是!
tr的文档! 说
 Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. 
我想你会得到正确的结果,如果你使用tr没有感叹号。
与空间
 str = "New School" str.parameterize.underscore => "new_school" 
没有空间
 str = "school" str.parameterize.underscore => "school" 
编辑: – 我们也可以通过'_'参数来参数化。
与空间
 str = "New School" str.parameterize('_') => "new_school" 
没有空间
 str = "school" str.parameterize('_') => "school" 
如果你有兴趣在蛇的情况下得到一个string,那么所提出的解决scheme就不太合适,因为你可能会得到连续的下划线和开始/结尾的下划线。
例如
 1.9.3-p0 :010 > str= " John Smith Beer " => " John Smith Beer " 1.9.3-p0 :011 > str.downcase.tr(" ", "_") => "__john___smith_beer_" 
下面的解决scheme会更好地工作:
 1.9.3-p0 :010 > str= " John Smith Beer " => " John Smith Beer " 1.9.3-p0 :012 > str.squish.downcase.tr(" ","_") => "john_smith_beer" 
squish是Rails提供的一个String方法
老问题,但…
对于所有的空白你可能想要更像这样的东西:
 "hey\t there world".gsub(/\s+/, '_') # hey_there_world 
 这会得到制表符和新行以及空格,并replace为一个_ 。 
正则expression式可以修改,以满足您的需求。 例如:
 "hey\t there world".gsub(/\s/, '_') # hey__there___world 
 str.downcase.tr(" ", "_") 
注意:不是“!”
你也可以做str.gsub(“”,“_”)
 str = "Foo Bar" str.tr(' ','').underscore => "foo_bar"