如何在Ruby中将字符串转换为小写或大写

42 浏览
0 Comments

如何在Ruby中将字符串转换为小写或大写

如何在Ruby中将字符串变成小写或大写?

admin 更改状态以发布 2023年5月21日
0
0 Comments

您可以通过打开irb并运行以下命令来查看字符串可用的所有方法:

"MyString".methods.sort

如果想要查看特定字符串可用的方法列表:

"MyString".own_methods.sort

我使用这个方法来发现对象中新奇有趣的事物,否则我可能不知道它们的存在。

0
0 Comments

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的文档

0