Ruby字符串 #
一、字符串概述 #
字符串是Ruby中最常用的数据类型之一。Ruby的字符串是可变的,支持多种创建方式和丰富的操作方法。
二、创建字符串 #
2.1 字符串字面量 #
ruby
s1 = 'Hello'
s2 = "Hello"
s3 = %q{Hello}
s4 = %Q{Hello}
s5 = %(Hello)
multiline = <<~TEXT
这是一个
多行字符串
TEXT
heredoc = <<-'END'
这里可以包含 #{变量} 而不会被插值
END
2.2 单引号 vs 双引号 #
ruby
name = "Ruby"
'Hello, #{name}'
"Hello, #{name}"
'Line 1\nLine 2'
"Line 1\nLine 2"
'Hello \\ World'
"Hello \\ World"
2.3 字符串方法创建 #
ruby
String.new
String.new("Hello")
"Hello".dup
"Hello".clone
2.4 Here Document #
ruby
text = <<~HTML
<html>
<head>
<title>#{title}</title>
</head>
<body>
#{content}
</body>
</html>
HTML
code = <<~RUBY
def hello
puts "Hello, World!"
end
RUBY
三、字符串插值 #
3.1 基本插值 #
ruby
name = "Ruby"
version = 3.3
"Hello, #{name}!"
"Ruby #{version}"
"1 + 2 = #{1 + 2}"
"#{name.upcase} is awesome"
3.2 格式化字符串 #
ruby
name = "Ruby"
age = 30
sprintf("Name: %s, Age: %d", name, age)
"Name: %s, Age: %d" % [name, age]
format("Name: %s, Age: %d", name, age)
"%.2f" % 3.14159
"%10s" % "Ruby"
"%-10s" % "Ruby"
"%05d" % 42
四、字符串操作 #
4.1 拼接 #
ruby
"Hello" + " " + "World"
"Hello" " " "World"
"Hello" << " " << "World"
"Hello".concat(" World")
["Hello", "World"].join(" ")
4.2 重复 #
ruby
"Ruby " * 3
"-" * 20
4.3 索引访问 #
ruby
s = "Hello, Ruby"
s[0]
s[0, 5]
s[0..4]
s[0...5]
s[-4..-1]
s[/Ruby/]
s[/R(.)/, 1]
4.4 切片 #
ruby
s = "Hello, World"
s.slice(0, 5)
s.slice(0..4)
s.slice!(-5..-1)
4.5 修改 #
ruby
s = "Hello"
s[0] = "h"
s[0, 5] = "Hi"
s << " World"
s.prepend("Say: ")
s.insert(5, " there")
s.replace("New string")
五、字符串方法 #
5.1 大小写转换 #
ruby
s = "Hello Ruby"
s.upcase
s.downcase
s.capitalize
s.swapcase
s.upcase!
s.downcase!
5.2 去除空白 #
ruby
s = " Hello "
s.strip
s.lstrip
s.rstrip
s.strip!
s.squeeze(" ")
5.3 查找 #
ruby
s = "Hello, Ruby World"
s.include?("Ruby")
s.start_with?("Hello")
s.end_with?("World")
s.index("Ruby")
s.rindex("o")
s =~ /Ruby/
s.match(/Ruby/)
s.match?(/Ruby/)
5.4 替换 #
ruby
s = "Hello, Ruby"
s.sub("Ruby", "World")
s.gsub("o", "0")
s.sub!(/Ruby/, "World")
s.gsub!(/[aeiou]/, "*")
s.tr("aeiou", "12345")
s.tr_s("a-z", "A-Z")
5.5 分割与连接 #
ruby
s = "apple,banana,cherry"
s.split(",")
s.split(/,\s*/)
s.split("", 3)
arr = ["apple", "banana", "cherry"]
arr.join(", ")
arr * ", "
5.6 反转与排序 #
ruby
s = "Ruby"
s.reverse
s.reverse!
s.chars.sort.join
5.7 长度与空判断 #
ruby
s = "Hello"
s.length
s.size
s.empty?
s.nil?
s.blank?
六、字符串转换 #
6.1 类型转换 #
ruby
"42".to_i
"3.14".to_f
"1,2,3".to_a
"hello".to_sym
"hello".chars
"hello".lines
"hello".bytes
"hello".codepoints
6.2 字符与ASCII #
ruby
"A".ord
65.chr
"Hello".bytes
"Hello".chars
"你好".bytes
"你好".chars
6.3 数值与字符串 #
ruby
42.to_s
42.to_s(16)
42.to_s(2)
3.14.to_s
Rational(1, 3).to_s
七、字符串编码 #
7.1 编码查看与转换 #
ruby
s = "你好"
s.encoding
s.encode("GBK")
s.force_encoding("GBK")
s.valid_encoding?
7.2 编码列表 #
ruby
Encoding.list
Encoding.name_list
Encoding.find("UTF-8")
Encoding.default_external
Encoding.default_internal
7.3 编码问题处理 #
ruby
s = "你好"
begin
s.encode("ASCII")
rescue Encoding::UndefinedConversionError => e
puts "编码转换失败: #{e}"
end
s.encode("ASCII", invalid: :replace, undef: :replace)
八、字符串比较 #
8.1 相等比较 #
ruby
"hello" == "hello"
"hello" === "hello"
"hello".eql?("hello")
"hello".equal?("hello")
8.2 大小比较 #
ruby
"a" <=> "b"
"apple" <=> "banana"
"Apple" <=> "apple"
"hello" <=> "hello"
8.3 大小写不敏感比较 #
ruby
"Hello".casecmp("hello")
"Hello".casecmp?("hello")
"Hello".downcase == "hello".downcase
九、正则表达式 #
9.1 匹配 #
ruby
s = "Hello, Ruby 3.3"
s =~ /Ruby/
s.match(/Ruby/)
s.match?(/Ruby/)
s =~ /(\d+)\.(\d+)/
$1
$2
9.2 捕获 #
ruby
s = "Ruby 3.3"
match = s.match(/(\w+)\s+(\d+)\.(\d+)/)
match[0]
match[1]
match[2]
match[3]
match.captures
match.names
9.3 替换 #
ruby
s = "Hello, Ruby"
s.sub(/Ruby/, "World")
s.gsub(/[aeiou]/, "*")
s.sub(/(\w+)/, '<\1>')
s.gsub(/(?<word>\w+)/, '[\k<word>]')
9.4 分割 #
ruby
"apple, banana; cherry".split(/[,;]\s*/)
"a1b2c3".split(/\d/)
十、实用示例 #
10.1 驼峰转换 #
ruby
def camel_case(str)
str.split('_').map(&:capitalize).join
end
def snake_case(str)
str.gsub(/([A-Z])/, '_\1').downcase.gsub(/^_/, '')
end
camel_case("hello_world")
snake_case("HelloWorld")
10.2 截断字符串 #
ruby
def truncate(str, length = 100, omission = "...")
return str if str.length <= length
str[0, length - omission.length] + omission
end
truncate("这是一段很长的文字,需要截断显示", 10)
10.3 单词统计 #
ruby
def word_count(str)
str.split(/\s+/).size
end
def char_count(str, char)
str.count(char)
end
word_count("Hello, Ruby World")
char_count("Hello", "l")
10.4 字符串模板 #
ruby
class Template
def initialize(template)
@template = template
end
def render(binding)
ERB.new(@template).result(binding)
end
end
require 'erb'
template = "Hello, <%= name %>! You are <%= age %> years old."
name = "Ruby"
age = 30
ERB.new(template).result(binding)
10.5 密码生成 #
ruby
def generate_password(length = 12)
chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a + '!@#$%^&*'.chars
Array.new(length) { chars.sample }.join
end
generate_password(16)
十一、字符串性能优化 #
11.1 冻结字符串 #
ruby
STRING = "constant string".freeze
def process
"literal string".frozen?
end
"literal string".frozen?
11.2 字符串构建 #
ruby
# 慢
result = ""
1000.times { result += "x" }
# 快
result = String.new
1000.times { result << "x" }
# 更快
result = +""
1000.times { result << "x" }
11.3 使用数组join #
ruby
# 慢
result = ""
items.each { |item| result += item.to_s }
# 快
items.map(&:to_s).join
十二、总结 #
本章我们学习了:
- 创建字符串:单引号、双引号、Here Document
- 字符串插值:#{}、sprintf、format
- 字符串操作:拼接、切片、修改
- 字符串方法:大小写、查找、替换、分割
- 字符串编码:UTF-8、GBK转换
- 正则表达式:匹配、捕获、替换
- 性能优化:freeze、字符串构建
接下来让我们学习Ruby的布尔类型!
最后更新:2026-03-27