Ruby中创建字符串的一些技巧小结

2019-09-25 09:46:56王旭

result is: (?-mix:world), Type is:Regexp

可以看出,world从第6个字符开始匹配

%w{String}用于将一个字符串以空白字符切分成一个字符串数组,进行较少替换
%W{String}用于将一个字符串以空白字符切分成一个字符串数组,进行较多替换

这两个应该是大家见过最多的,用这个方式构造数组,可以省下一些逗号,Ruby真 是会惯坏大家,以后大家都不用标点符号了。

同样给一个简单的例子:


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下的记事本,这里我就不列结果了(那是一个大家熟悉的窗口)