文章目录
String
''
和 ""
单引号标记
: 不允许替换,且只允许使用\\
和\
两个反斜线符号。双引号标记
: 允许替换
和使用反斜线
符号,支持更多的转义字符
#{ expr }
双引号的字符串才可以使用
- 可以使用序列
#{ expr }
替换任意 Ruby 表达式的值为一个字符串。 - 在这里,expr 可以是任意的 Ruby 表达式。
text = "hello world"
text1 = "#{text + ' new'}"
print text1
# 输出 hello world new
多行字符串
"Here Document"
是指建立多行字符串。在 << 之后,您可以指定一个字符串或标识符来终止字符串,且当前行之后直到终止符为止的所有行是字符串的值。
如果终止符用引号括起,引号的类型决定了面向行的字符串类型。请注意<< 和终止符之间必须没有空格。
print <<EOF
这是第一种方式创建here document 。
多行字符串。
EOF
text = <<EOF
这是第一种方式创建here document 。
多行字符串。
EOF
print text
字符编码
取值 | 含义 | |
---|---|---|
a | ASCII (与 none 相同)。这是默认的。 | |
e | EUC。 | |
n | None (与 ASCII 相同) | |
u | UTF-8。 |
在程序的开头改变字符集
$KCODE
注意:这个已经不使用了
$KCODE = 'u'
程序运行的时候会有如下的错误
warning: variable $KCODE is no longer effective; ignored
常用 api
大小
str.length
str = "Hello"
puts str.length # 5
str.empty?
是否为空
str = "Hello"
puts str.empty? # false
str * integer
把字符串 str
重复 integer
次
str = "one "
puts str * 3
one one one
拼接
str + other_str
字符串拼接
str = "one"
puts str + "two"
onetwo
str.concat(other_str)
str = "hello"
puts str.concat(" world!") # hello world!
比较
相等判断 str <=> other_str
字符串比较,比较是区分大小写的
- 小于:-1
- 等于:0
- 大于:1()
相等判断 str == obj
相等性比较
- 如果 obj 不是字符串,则返回 false,
- 如果 str <=> obj,则返回 true,返回 0。
相等判断 str.eql?(other)
str = "Hello"
puts str.eql?("hello") # false
puts str.eql?("Hello") # true
puts str.eql?("123") # false
str =~ obj
- 根据正则表达式模式 obj 匹配 str。
- 返回匹配开始的位置,否则返回 false。
字符串截取
# 注意返回的是ASCII码而不是字符
str[position]
str[start, length]
str[start..end]
str[start...end]
str = "hello world!"
puts str[1] # e
puts str[1, 2] # el
puts str[1..3] # ell
puts str[1...3] # el
大小写
首字母大写 str.capitalize
str.capitalize!
str = "hello"
puts str.capitalize # Hello
小写字母 str.downcase
str.downcase!
str = "Hello"
puts str.downcase # hello
大写 str.upcase
str.upcase!
str = "Hello"
puts str.upcase # HELLO
大小写转换 str.swapcase
str.swapcase!
str = "Hello"
puts str.swapcase # hELLO
str.chop
移除最后一个字符
str = "hello"
puts str.chop # hell
替换 str.replace(other_str)
str = "Hello"
puts str.replace("new hello") # new hello
反转 str.reverse
str.reverse!
str = "Hello"
puts str.reverse # olleH