Ruby 的 %Q, %q, %W, %w, %x, %r, %s, %i

Published on:

有時候在看其他人的 Ruby 程式碼時,常常發現有 %w, %r 等 % 開頭的程式碼。上網查了一下,才知道這些叫做 Percent literals(或Percent Strings)

以下內容是改寫自 %Q, %q, %W, %w, %x, %r, %sRuby 里的 %Q, %q, %W, %w, %x, %r, %s, %i (译)

執行環境:

  • ruby: 2.2.2
  • console: irb

%Q


代替雙引號字串,如果在字串中有很多雙引號的時候很好用

>> what_frank_said = 'Hello!'
=> "Hello!"

>> %Q(Joe said: "Frank said: "#{what_frank_said}"")
=> "Joe said: \"Frank said: \"Hello!\"\""

>> puts %Q(Joe said: "Frank said: "#{what_frank_said}"")
Joe said: "Frank said: "Hello!""
=> nil

也可以省略 Q

Ruby Style Guide 建議使用 %(),因為比 %Q()

>> what_frank_said = 'Hello!'
=> "Hello!"

>> %(Joe said: "Frank said: "#{what_frank_said}"")
=> "Joe said: \"Frank said: \"Hello!\"\""

>> puts %(Joe said: "Frank said: "#{what_frank_said}"")
Joe said: "Frank said: "Hello!""
=> nil

%q


代替單引號字串,如果在字串中有很多單引號的時候用

>> %q(Joe said: 'Frank said: '#{what_frank_said} ' ')
=> "Joe said: 'Frank said: '\#{what_frank_said} ' '"

>> puts %q(Joe said: 'Frank said: '#{what_frank_said} ' ')
Joe said: 'Frank said: '#{what_frank_said} ' '

=> nil

%W


產生用雙引號包起來的字串陣列(用空白做分隔,空白需要用 \ 符號跳過)

>> %W(a b c\ d \#e #{1}f)
=> ["a", "b", "c d", "#e", "1f"]

%w


產生用單引號包起來的字串陣列(用空白做分隔,空白需要用 \ 符號跳過)

可以觀察與使用 %W 出來的差異

>> %w(a b c\ d \#e #{1}f)
=> ["a", "b", "c d", "\\#e", "\#{1}f"]

%x


使用``方法執行一段 shell script 並回傳標準輸出的結果

>> %x(echo foo:#{'Foo'})
=> "foo:Foo\n"

%r


產生正規表示式

>> %r(/home/#{'Foo'})
=> /\\/home\\/Foo/

%s


產生 symbol,但不會對表示式等內容作轉換

>> %s(foo)
=> :foo
>> %s(foo bar)
=> :"foo bar"
>> %s(#{foo} bar)
=> :"\#{foo} bar"

%i


產生 symbol 陣列

>> %i(a b c)
=> [:a, :b, :c]

除了用 () 也可以用其他非數字字母的符號或是成對的符號代替:

%Q(...) 
%Q[...]
%Q!...!
%Q+...+
%Q{...}
%Q-...-

參考:

%Q, %q, %W, %w, %x, %r, %s

Ruby 里的 %Q, %q, %W, %w, %x, %r, %s, %i (译)

Ruby : General Delimited Input

Ruby Doc - Percent Strings

Ruby Style Guide Percent Literals

Ruby Style Guide 百分比字面

Comments

comments powered by Disqus