ruby字符串:Ruby 字符串处理

Ruby将串像数字样处理.我们用单引号('...')或双引号("...")将它们括起来.
ruby> "abc"
"abc"
ruby> 'abc'
"abc"

单引号和双引号在某些情况下有区别作用.个由双引号括起来串允许个前置斜杠引出,而且可以用#{}内嵌表达式.而
单引号括起来串并不会对串作任何解释;你看到是什么便是什么.几个例子:
ruby> pr "a\nb\nc","\n"
a
c
nil
ruby> pr '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)]
pr "guess? "
while guess = STDIN.gets
guess.chop!
guess secret
pr "You win!\n"


pr "Sorry, you lose.\n"
end
pr "guess? "
end
pr "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成功率,也许我本该做得好点.)
Tags:  字符串处理函数 字符串处理 ruby字符串截取 ruby字符串

延伸阅读

最新评论

发表评论