---
title: "ruby-(%Q-%q-%W-%w-%r-%s-%x)说明"
author: "sitoto"
date: "2012-07-17T09:27:42Z"
tags: []
categories: ["编程语言"]
slug: "ruby-q-q-w-w-r-s-x"
draft: false
lastmod: "2012-07-17T09:28:58Z"
id: 1596022
url: "https://sitoto.iteye.com/blog/1596022"
---

%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:

```java
>> %Q(Joe said: "Frank said: "#{what_frank_said}"")
=> "Joe said: "Frank said: "Hello!"""
```


The parenthesis “(…)” can be replaced with any other non-alphanumeric characters and non-printing characters (pairs), so the following commands are equivalent:

```java
>> %Q!Joe said: "Frank said: "#{what_frank_said}""!
>> %Q[joe said: "frank said: "#{what_frank_said}""]
>> %Q+Joe said: "Frank said: "#{what_frank_said}""+
```


You can use also:

```java
>> %/Joe said: "Frank said: "#{what_frank_said}""/
=> "Joe said: "Frank said: "Hello!"""
```


%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.

```java
>> %q(Joe said: 'Frank said: '#{what_frank_said} ' ')
=> "Joe said: 'Frank said: '\#{what_frank_said} ' '"
```


%W
Used for double-quoted array elements.The syntax is similar to %Q

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

```java
>> %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.

```java
>> %x(echo foo:#{foo})
=> "foo:Foo\n"
```


%r
Used for regular expressions.The syntax is similar to %Q.

```java
>> %r(/home/#{foo})
=> "/\\/home\\/Foo/"
```


%s
Used for symbols.It’s not subject to expression substitution or escape sequences.

```java
>> %s(foo)
=> :foo
>> %s(foo bar)
=> :"foo bar"
>> %s(#{foo} bar)
=> :"\#{foo} bar"
```


Thanks, Ivan