Ruby provides several ways to create a String
object. The most common way is using single or double quotes to create a "string literal":
s1 = 'Hello'
s2 = "Hello"
The main difference is that double-quoted string literals are a little bit more flexible as they support interpolation and some backslash escape sequences.
There are also several other possible ways to create a string literal using arbitrary string delimiters. An arbitrary string delimiter is a %
followed by a matching pair of delimiters:
%(A string)
%{A string}
%<A string>
%|A string|
%!A string!
Finally, you can use the %q
and %Q
sequence, that are equivalent to '
and "
":
puts %q(A string)
# A string
puts %q(Now is #{Time.now})
# Now is #{Time.now}
puts %Q(A string)
# A string
puts %Q(Now is #{Time.now})
# Now is 2016-07-21 12:47:45 +0200
%q
and %Q
sequences are useful when the string contains either single quotes, double quotes, or a mix of both. In this way, you don't need to escape the content:
%Q(<a href="/profile">User's profile<a>)
You can use several different delimiters, as long as there is a matching pair:
%q(A string)
%q{A string}
%q<A string>
%q|A string|
%q!A string!