|
|
Ruby将字符串像数字一样处理.我们用单引号('...')或双引号("...")将它们括起来.
ruby> "abc" "abc" ruby> 'abc' "abc" |
单引号和双引号在某些情况下有不同的作用.一个由双引号括起来的字符串允许字符由一个前置的斜杠引出,而且可以用#{}内嵌表达式.而
单引号括起来的字符串并不会对字符串作任何解释;你看到的是什么便是什么.几个例子:
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的字符串操作比C更灵巧,更直观.比如说,你可以用+把几个串连起来,用*把一个串重复好几遍:
ruby> "foo" + "bar" "foobar" ruby> "foo" * 2 "foofoo" |
相比之下,在C里,因为需要精确的内存管理,串联字符串要笨拙的多:
char *s = malloc(strlen(s1)+strlen(s2)+1); strcpy(s, s1); strcat(s, s2); /* ... */ free(s); |
但对于Ruby,我们不需要考虑字符串的空间占用问题,这令到我们可以从烦琐的内存管理中解脱出来.
下面是一些字符串的处理,
串联:
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 |
注意:在Ruby 1.0里,以上结果以大写字母出现.
好,让我们来试试这些特性.下面是一个猜词的谜题,可能"谜题"这个词用在下面的东西上太酷了一点;-)
# save this as guess.rb words = ['foobar', 'baz', 'quux'] secret = words[rand(3)] print "guess? " while guess = STDIN.gets guess.chop! if guess == secret print "You win!\n" break else print "Sorry, you lose.\n" end print "guess? " end print "The word was ", secret, ".\n" |
现在,别太担心代码细节了.下面是谜题程序运行的一个对话.
% ruby guess.rb guess? foobar Sorry, you lose. guess? quux Sorry, you lose. guess? ^D The word was baz. |
(考虑到1/3的成功率,也许我本该做得好一点.) |
|
版权声明:RUBY文档中心的所有文章标明[原创]的均为本站作品,版权属RUBY中文化计划,若转载请注明;标明[翻译]的其外文版权归原作者,译文版权属RUBY中文化计划;标明[转贴]的,若原作者感到侵犯了他的著作权,那么请及时跟主持人联系,我们会尽快更正。 | |
|