Ruby语言作为一种完全面向对象的解释型脚本语言,可以帮助我们简单实现许多功能需求。其灵活性逐步的被广大编程人员所接受。#t#
Ruby字符串可以像数字一样处理.我们用单引号('...')或双引号("...")将它们括起来.
- ruby> "abc"
- "abc"
- ruby> 'abc'
- "abc"
单引号和双引号在某些情况下有不同的作用.一个由双引号括起来的字符串允许字符由一个前置的斜杠引出,而且可以用#{}内嵌表达式.而单引号括起来的字符串并不会对Ruby字符串作任何解释;你看到的是什么便是什么.几个例子:
- ruby> print "a\nb\nc","\n"
- a
- 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里,因为需要精确的内存管理,串联Ruby字符串要笨拙的多:
- char *s = malloc(strlen
(s1)+strlen(s2)+1);- strcpy(s, s1);
- strcat(s, s2);
- /* ... */
- free(s);
但对于Ruby字符串,我们不需要考虑字符串的空间占用问题,这令到我们可以从烦琐的内存管理中解脱出来.
下面是一些字符串的处理,
串联:
- ruby> word =
"fo" + "o"- "foo"
重复:
- ruby> wordword = 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里,以上结果以大写字母出现.
好,让我们来试试这些Ruby字符串特性.下面是一个猜词的谜题,可能"谜题"这个词用在下面的东西上太酷了一点;-)
- # 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字符串代码细节了.下面是谜题程序运行的一个对话。
- % ruby guess.rb
- guess? foobar
- Sorry, you lose.
- guess? quux
- Sorry, you lose.
- guess? ^D
- The word was baz.