%Q
用於替代雙引號的字串. 當你需要在字串裡放入很多引號時候, 可以直接用下面方法而不需要在引號前逐個新增反斜槓 (\")
>> %Q(Joe said: "Frank said: "#{what_frank_said}"") => "Joe said: "Frank said: "Hello!"""
(
...)
也可用其他非數字字母的符號或成對的符號代替, 諸如[
...]
, !
...!
, +
...+
,{
...}
, <
...>
等.
以下寫法全部與上面等效:
>> %Q!Joe said: "Frank said: "#{what_frank_said}""! >> %Q[Joe said: "Frank said: "#{what_frank_said}""] >> %Q+Joe said: "Frank said: "#{what_frank_said}""+
除此之外還可省略Q
寫作:
>> %/Joe said: "Frank said: "#{what_frank_said}""/ => "Joe said: "Frank said: "Hello!"""
%q
與%Q
類似, 但是表示的是單引號字串
>> %q(Joe said: 'Frank said: '#{what_frank_said} ' ') => "Joe said: 'Frank said: '\#{what_frank_said} ' '"
%W
語法近似於%Q
, 用於表示其中元素被雙引號括起的陣列.
>> %W(#{foo} Bar Bar\ with\ space) => ["Foo", "Bar", "Bar with space"]
%w
用於表示其中元素被單引號括起的陣列. 比較奇怪的是\
(斜槓空格)會被轉化成(空格), 但是其他的內容不會.
>> %w(a b c\ d \#e #{1}f) => ["a", "b", "c d", "\\#e", "\#{1}f"]
%x
使用`方法執行一段shell指令碼並返回標準輸出內容.
>> %x(echo foo:#{foo}) => "foo:Foo\n"
%r
語法近似於%Q
, 用於正規表示式.
>> %r(/home/#{foo}) => "/\\/home\\/Foo/"
%s
用於表示symbol, 但是不會對其中表示式等內容進行轉化
>> %s(foo) => :foo >> %s(foo bar) => :"foo bar" >> %s(#{foo} bar) => :"\#{foo} bar"
%i
Ruby 2.0 之後引入的語法, 用於生成一個symbol陣列
2.0.0p247 :014 > %i(a b c) => [:a, :b, :c]