Ruby将字符串像数字一样处理。我们用单引号('...')或双引号("...")将它们括起来。单引号和双引号在某些情况下有不同的作用。一个由双引号括起来的字符串允许使用转义字符,就是反斜杠开头的字符,而且可以用#{}内嵌表达式.而单引号括起来的字符串并不会对字符串作任何解释。
ruby> print "a\nb\nc","\n"
a
b
c
nil
ruby> print 'a\nb\n',"\n"
a\nb\nc
nil
ruby> "\n"
"\n"
ruby> '\n'
"\\n"
ruby> "\001"
"\001"
ruby> '\001'
"\\001"
ruby> "abcd #{5*3} efg"
"abcd 15 efg"
ruby> var = " abc "
" abc "
ruby> "1234#{var}5678"
"1234 abc 5678"
字符串常用处理有:
串联:
ruby> word = "fo" + "o"
"foo"
重复:
ruby> word = word * 2
"foofoo"
抽取字符(注意:在Ruby里,字符被视为整数):
ruby> word[0]
102 # 102 is ASCII code of `f'
ruby> word[-1]
111 # 111 is ASCII code of `o'
(负的索引指从字符串尾算起的偏移量,而不是从串头.)
提取子串:
ruby> herb = "parsley"
"parsley"
ruby> herb[0,1]
"p"
ruby> herb[-2,2]
"ey"
ruby> herb[0..3]
"pars"
ruby> herb[-5..-2]
"rsle"
检查相等:
ruby> "foo" == "foo"
true
ruby> "foo" == "bar"
false
表达式插补(expression interpolation):
字符串中的#{expression}序列会被替换为expression表达式的值。
ruby> var = " abc "
" abc "
ruby> "1234#{var}5678"
"1234 abc 5678"