13

我正在尝试编写一个助手来将字符串从 转换"something_like_this""Something like this"。我习惯使用"something_like_this".titlecase它,"Something Like This"但除了第一个之外,我坚持将每个大写字母都小写。

我想我正在寻找这样的东西:

def write_sentence
  string.titlecase.gsub!(/UPPERCASE-TO-LOWERCASE-EXCEPT-FIRST/)
  #that should be something to lowercase everything except the first letter
  return string
end

因此,在视图中,我可以编写string.write_sentence并让它返回我想要的内容。有什么想法吗?

谢谢!

编辑

我应该提一下,字符串有时可能只有一个单词,在这种情况下,字符串应该从 转换"something""Something".

4

3 回答 3

37

尝试这个,

"something_like_this".humanize

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-humanize

于 2013-03-24T23:48:12.333 回答
0

你可以使用capitalize

greeting = 'HELLO, WORLD!'
puts greeting.capitalize
> Hello, world!
于 2021-12-22T17:48:17.407 回答
-1

最简单的解决方案可能是抓住第一个字母,将其大写,然后将它与一个新字符串放在一起,其中第一个字母已被删除。然后只需运行正常替换即可更改_. 这里不需要任何花哨的正则表达式。

于 2013-03-24T23:47:15.417 回答