%{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
新聞熱點
疑難解答