阅读量:113
在 Ruby 中,可以使用多种方法来转换字符串。以下是一些常见的字符串转换方法:
- 转换为小写:
downcase方法将字符串中的所有大写字母转换为小写字母。
str = "Hello World"
lowercase_str = str.downcase
puts lowercase_str # 输出 "hello world"
- 转换为大写:
upcase方法将字符串中的所有小写字母转换为大写字母。
str = "hello world"
uppercase_str = str.upcase
puts uppercase_str # 输出 "HELLO WORLD"
- 交换大小写:
swapcase方法将字符串中的所有大写字母转换为小写字母,反之亦然。
str = "HeLLo WoRLD"
swapped_case_str = str.swapcase
puts swapped_case_str # 输出 "hELlO wORLD"
- 替换字符串中的内容:
gsub方法用于替换字符串中的一部分内容。
str = "I like apples"
replaced_str = str.gsub("apples", "bananas")
puts replaced_str # 输出 "I like bananas"
- 删除字符串中的空白字符:
strip方法用于删除字符串首尾的空白字符(包括空格、制表符和换行符)。
str = " Hello World "
stripped_str = str.strip
puts stripped_str # 输出 "Hello World"
- 截取字符串:
slice方法用于截取字符串的一部分。
str = "Hello World"
substring = str.slice(0, 5)
puts substring # 输出 "Hello"
这只是 Ruby 字符串处理中的一些基本方法,还有其他许多方法可以用于处理字符串,例如 length(获取字符串长度)、+(连接字符串)等。你可以查阅 Ruby 官方文档以了解更多关于字符串处理的方法。