The difference between double quotes and single quotes wrapping strings in Ruby

Table of contents:

        preface

        Use "" and '' to output a string respectively

        Use "" and '' respectively to output a string and add escape characters

        summary

preface:

In Ruby, strings can be wrapped using "" and '' wrappers. Some readers think that they are similar. After all, "" and '' are wrapped in a string, but the characters that wrap them are different. But this is not the case. In this chapter, we will explain in detail the difference between using "" and '' to wrap strings.

Use "" and '' respectively to output a string:

Let's first take a look at an example, the effect of outputting a string wrapped in "" and a string wrapped in '':

Output a string wrapped with "":

print("Hello Ruby")

Output a string wrapped in '':

print('Hello Ruby')

We use the print method to output these two strings respectively. When executed, their results are the same, both are "Hello Ruby".

Use "" and '' respectively to output a string and add escape characters:

But once we add an escape character "\n" to the end of these two strings to represent a newline, we get two different results.

Output a string wrapped with "":

print("Hello Ruby\n")

Output a string wrapped in '':

print('Hello Ruby\n')

Let's take a look at the output of these two strings:

Output the result of a string wrapped in "":

Output: Hello Ruby

Output the result of a string wrapped in '':

Output: Hello Ruby\n

From the above, if the string wrapped with "" has escape characters, the escape characters will be escaped. But if we use '' to wrap the string, if there are escape characters in the string, it will not escape the escape characters, but set the escape characters as part of the string. Let's look at another example where we use a variable to store and output these two strings.

Here we create a string variable that stores "" packages. This variable is called "a", as shown in the following figure:

a = "Hello Ruby\n"

Then we use the print method to output.

a = "Hello Ruby\n"
print a

Let’s take a look at the output again:

Output: Hello Ruby

We then use '' to wrap the string, and follow the above analogy to output the result.

a = 'Hello Ruby\n'
print a

Output: Hello Ruby\n

From this we find that the above example has the same effect as directly outputting two strings.

summary:

After reading the above example, we can draw a conclusion that the escape characters in the string wrapped with "" will be escaped, while the escape characters of the characters using '' are part of the string, it will not Escaped, but a single string. This is the difference between using "" to wrap a string and '' to wrap a string in Ruby. Hope this article is helpful to you.

Guess you like

Origin blog.csdn.net/m0_68824353/article/details/126022128