%{String} 用于创建一个使用双引号括起来的字符串
%Q{String} 用于创建一个使用双引号括起来的字符串
复制代码 代码如下:
str=<<END_OF_STRING
a string
END_OF_STRING
%Q!Some String of “Characters”! <==> ” Some String of /”Characters/” “
%q{String} 用于创建一个使用单引号括起来的字符串
%q!Some String of “Characters”! <==> ‘Some String of Characters'
%r{String} 用于创建一个正则表达式字面值
%r{/usr/bin/} <==> ///usr//bin///
%w{String} 用于将一个字符串以空白字符切分成一个字符串数组,进行较少替换
%W{String} 用于将一个字符串以空白字符切分成一个字符串数组,进行较多替换
%W(North South East West) <==> ["North", "South", "East", "West"]
%s{String} 用于生成一个符号对象
%x{String} 用于执行String所代表的命令
%x{ ls /usr/local } <==> `ls /usr/local`
PS:上面几个%表示法中用{}扩住了String,其实这个{} 只是一种分割符,可以换成别的字符,比如(),那么%表示法就是%(String),当然还可以是别的字符,对于非括号类型的分割符,左右两边要相同, 如%!String!
下面我对这些表示法简单举几个例子:
%{String}用于创建一个使用双引号括起来的字符串
这个表示法与%Q{String}完全一样,这边直接句个例子看结果:
复制代码 代码如下:
result = %{hello}
puts "result is: #{result}, Type is:#{result.class}"
结果: result is: hello, Type is:String
%Q{String}用于创建一个使用双引号括起来的字符串
%q{String}用于创建一个使用单引号括起来的字符串
从说明中可以看出这两个表示法的区别就是一个使用双引号,一个使用单引号。使用双引号的字符串会对字符串中的变量做较多替换,而单引号则做较少的替换,具 体看例子。先看%Q{String}:
复制代码 代码如下:
world = "world"
result = %Q{hello #{world}}
puts "result is: #{result}, Type is:#{result.class}"
结果: result is: hello world, Type is:String
换成%q{String}:
复制代码 代码如下:
world = "world"
result = %q{hello #{world}}
puts "result is: #{result}, Type is:#{result.class}"
结果:
result is: hello #{world}, Type is:String
从上面的结果可以看出,较少替换的情况下,#{world}被解析成了字符串,而不会去计算这个变量中的值。
%r{String}用于创建一个正则表达式字面值
就像使用/reg/方式一样,看代码:
复制代码 代码如下:
result = %r{world}
puts result =~ "hello world"
puts "result is: #{result}, Type is:#{result.class}"
结果: 6
result is: ("codetitle">复制代码 代码如下:
result = %w{hello world}
puts "result is: #{result}, Type is:#{result.class}, length is:#{result.length}"
结果: result is: helloworld, Type is:Array, length is:2
%s{String}用于生成一个符号对象
直接先上代码:
复制代码 代码如下:
result = %s{hello world}
puts "result is: #{result}, Type is:#{result.class}"
sym = :"hello world"
puts "the two symbol is the same: #{sym == result}"
结果:
result is: hello world, Type is:Symbol
the two symbol is the same: true
可以看出,这两中方式生成的symbol对象完全一样
%x{String}用于执行String所代表的命令
比如:
%x{notepad.exe}可以启动windows下的记事本,这里我就不列结果了(那是一个大家熟悉的窗口)
Ruby,创建字符串技巧
更新日志
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】