如何在 Ruby 中将字符串转换为小写或大写 [英] How to convert a string to lower or upper case in Ruby

查看:96
本文介绍了如何在 Ruby 中将字符串转换为小写或大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Ruby 中获取字符串并将其转换为小写或大写?

How do I take a string and convert it to lower or upper case in Ruby?

推荐答案

Ruby 有一些改变字符串大小写的方法.要转换为小写,请使用 downcase:

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase:

"hello James!".downcase    #=> "hello james!"

类似地,upcase 将每个字母大写,capitalize 将字符串的第一个字母大写,其余字母小写:

Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

"hello James!".upcase      #=> "HELLO JAMES!"
"hello James!".capitalize  #=> "Hello james!"
"hello James!".titleize    #=> "Hello James!"

如果你想就地修改一个字符串,你可以给这些方法中的任何一个添加一个感叹号:

If you want to modify a string in place, you can add an exclamation point to any of those methods:

string = "hello James!"
string.downcase!
string   #=> "hello james!"

有关详细信息,请参阅字符串文档.

Refer to the documentation for String for more information.

这篇关于如何在 Ruby 中将字符串转换为小写或大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆