程式扎記: [ 文章收集 ] %Q, %q, %W, %w, %x, %r, %s

標籤

2014年11月27日 星期四

[ 文章收集 ] %Q, %q, %W, %w, %x, %r, %s

Source From Here
%Q
This is an alternative for double-quoted strings, when you have more quote characters in a string.Instead of putting backslashes in front of them, you can easily write:
>> what_john_said="Hello"
=> "Hello"
>> %Q(Joe said: "John said:"#{what_john_said}"")
=> "Joe said: \"John said:\"Hello\"\""

The parenthesis “(…)” can be replaced with any other non-alphanumeric characters and non-printing characters (pairs), so the following commands are equivalent:
>> %Q!Joe said: "John said: "#{what_john_said}""!
>> %Q[Joe said: "John said: "#{what_john_said}""]
>> %Q+Joe said: "John said: "#{what_john_said}""+

You can use also:
>> %/Joe said: "John said: "#{what_john_said}""/

%q
Used for single-quoted strings.The syntax is similar to %Q, but single-quoted strings are not subject to expression substitution or escape sequences.
>> %q(Joe said: 'John said: '#{what_john_said} ' ')
=> "Joe said: 'john said: '\#{what_john_said} ' '"

%W
Used for double-quoted array elements.The syntax is similar to %Q
>> foo = "Foo"
=> "Foo"
>> %W(#foo Bar Bar\ with\ space)
=> ["#foo", "Bar", "Bar with space"]

%w
Used for single-quoted array elements.The syntax is similar to %W, but single-quoted elements are not subject to expression substitution or escape sequences.
>> %w(#{foo} Bar Bar\ with\ space)
=> ["\#{foo}", "Bar", "Bar with space"]

%x
Uses the ` method and returns the standard output of running the command in a subshell.The syntax is similar to %Q.
>> %x(echo foo:#{foo})
=> "foo:Foo\n"

%r
Used for regular expressions.The syntax is similar to %Q.
>> regr = %r(/home/#{foo}/(.*))
=> /\/home\/Foo\/(.*)/
>> regr.class.name
=> "Regexp"
>> mth = regr.match("/home/Foo/test")
=> #<MatchData "/home/Foo/test" 1:"test">
>> mth[0]
=> "/home/Foo/test"
>> mth[1]
=> "test"

%s
Used for symbols. It’s not subject to expression substitution or escape sequences.
>> %s(foo)
=> :foo
>> %s(foo bar)
=> :"foo bar"
>> %s(#{foo} bar)
=> :"\#{foo} bar"


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!