如何在Ruby中将字符串转换为小写或大写
Ruby有几种更改字符串大小写的方法。要转换为小写,请使用downcase
:
"hello James!".downcase #=> "hello james!"
同样,upcase
将每个字母都大写,而capitalize
大写字符串的第一个字母,但将其余部分小写:
"hello James!".upcase #=> "HELLO JAMES!" "hello James!".capitalize #=> "Hello james!" "hello James!".titleize #=> "Hello James!" (Rails/ActiveSupport only)
如果您想直接修改字符串,可以在这些方法中的任何一个方法中添加感叹号:
string = "hello James!" string.downcase! string #=> "hello james!"
有关更多信息,请参见String的文档。