每天一条Ruby小道之与字符串共舞

1,字符串表达方式
[code]
s = 'abc'
s = "abc"
s = %q[abc]
s = %Q[abc]
s = %q(abc)
s = %q{abc}
s = %q<abc>
s = %q:abc:
s = %q*abc*
...
[/code]
上面的例子都是合法的字符串表达方式。
当使用%q或%Q符号表示字符串时,界定符可以是任何成对界定符([]、<>等)或非数字、非空格、可打印的非成对单字符(:、#、@等)。

2,here-document
对较长的多行字符串,可以使用here-document来的方式表示:
[code]
str = <<EOF
Once upon a midnight dreary,
While I pondered weak and weary,...
EOF
[/code]
<<符号后面接一个结束符,用来标识在两个结束符之间的内容为字符串str的内容。
默认时here-document为一个双引号标识的字符串,这样可以在字符串里嵌入\t,\n,#{}等特殊符号并计算其值
而我们可以显示指定单引号的结束符来让我们得到一个单引号标识的字符串:
[code]
str = <<'EOF'
This isn't a tab: \t
and this isn't a newline: \n
EOF
[/code]
默认时在结束符前加空格缩进或者在结束符后加空格的话,here-document不会认为这是合法的结束符。
但是我们可以使用<<-来删除结束符前面的空格缩进,但不会删除后面的空格和其他行的缩进:
[code]
str = <<-EOF
Each of these lines
starts with a pair
of blank spaces.
EOF
[/code]
我们有这种形式的here-document应用:
[code]
class String
def margin
arr = self.split("\n")
arr.map! {|x| x.sub!(/\s*\|/, "")}
str = arr.join("\n")
self.replace(str)
end
end

str = <<end.margin
|This here-document has a "left margin"
|at the vertical bar on each line.
|
| We can do inset quotations,
| hanging indentions, and so on.
end
[/code]
这样得到的str会调用margin方法来去掉每行开始的缩进和“|”字符。

here-document是我们给class_eval方法传参时经常用到的,比如ActiveRecord的associations.rb里的一段代码:
[code]
class_eval <<-end_eval
alias_method :#{old_method}, :destroy_without_callbacks
def destroy_without_callbacks
#{reflection.name}.clear
#{old_method}
end
end_eval
[/code]

3,处理多行字符串
[code]
str = "Once upon\na time...\nThe End\n"
num = 0
str.each do |line|
num += 1
print "Line #{num}: #{line}"
end
[/code]
可以使用each来对多行字符串进行一行一行的处理,比如读取一个文件,每行加上行号。
上面的代码得到的str打印出来为:
Line 1: Once upon
Line 2: a time...
Line 3: The End

4,字符串与字节
由于目前Ruby不是完全国际化的,一个ASCII字符本质上是一个byte,而字符串则是字节序列,我们可以这样按顺序处理字符串:
[code]
str = "ABC"
str.each_byte {|char| print char, " "}
# 结果为65 66 67
[/code]
如果字符串里包含中文的话,一个中文字符会用两个byte来存储,应该为Unicode形式,后面第四章会详细讨论国际化和Unicode。

5,字符串里嵌入表达式
变量可以用#{}来在字符串里求值:
[code]
a = 1
puts "a = #{a}"
[/code]
完整的语句也可以:
[code]
str = "The answer is #{ def factorial(n)
n == 0 ? 1 : n*factorial(n-1)
end

answer = factorial(3) * 7}, of course."
[/code]
对于全局变量、类变量和实例变量在字符串中的使用:
[code]
$a = 1
@@b = 2
@c = 3
print "$a = #$a and @@b = #@@b and @c = #@c."
[/code]

6,字符串迟求值
proc
[code]
str = proc {|a,b| "a = #{a}, b = #{b}"}
str.call(1, 2)
# => "a = 1, b = 2"
[/code]
eval
[code]
str = 'a = #{a}, b = #{b}'
a, b = 1, 2
eval('"' + str + '"')
# => "a = 1, b = 2"
[/code]
binding
[code]
bind = proc do
a, b = 1, 2
binding
end.call
eval('"' + str + '"', bind)
# => "a = 1, b = 2"
[/code]

后面就是一些String的api讲解,这里就不介绍了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值