Ruby - String String Literals

Introduction

You can delimit strings by %q/ and / for single-quoted strings and either %Q/ and / or %/ and / for double-quoted strings.

Ruby can delimit back-quoted strings, regular expressions, symbols, and arrays of either single-quoted or double-quoted strings.

Here is a reference to these string literal delimiters:


%q/    /    # single-quoted 
%Q/    /    # double-quoted 
%/     /    # double-quoted 
%w/    /    # array 
%W/    /    # array double-quoted 
%r|    |    # regular expression 
%s/    /    # symbol 
%x/    /    # operating system command 

You may choose which delimiters to use.

I have used / except with the regular expression where I have used | (since / is the "normal" regular expression delimiter).

Here is an example of these literals in use:

Demo

p %q/test cat #{1+2}/        #=> "test cat \#{1+2}" 
p %Q/test cat #{1+2}/        #=> "test cat 3" 
p %/test cat #{1+2}/         #=> "test cat 3" 
p %w/test cat #{1+2}/        #=> ["test", "cat", "\#{1+2}"] 
p %W/test cat #{1+2}/        #=> ["test", "cat", "3"] 
p %r|^[a-z]*$|               #=> /^[a-z]*$/ 
p %s/test/                   #=> :test 
p %x/dir/                    #=> " Volume in drive C is OS [etc...]"
# from w w w.  j ava  2s. c  o m

Result