Ruby single and double quotes

I was in Ruby recently and came from Python, where single and double quotes didn't matter how the code worked, as far as I know.

I moved to Ruby to see how it works and to explore the similarities between Ruby and Python.

I used single-frame strings once and noticed this:

hello = 'hello'
x = '#{hello} world!'
puts x

He returned '#{hello} world!', not 'hello world!'.

Noticing this, I tried double quotes and the problem was fixed. Now I'm not sure why this is so.

Have single and double quotes changed or is it because of my editor (Sublime text 3)? I also use Ruby version 2.0 if it works differently in previous versions.

+4
source share
6 answers

Ruby , #{} Ruby. ( , ).

var = "hello"
"#{var} world" #=> "hello world"
'#{var} world' #=> "#{var} world"

Ruby :

%Q() # behaves like double quotes
%q() # behaves like single quotes

:

%Q(#{var} world) #=> "hello world"
%q(#{var} world) #=> "#{var} world"
+7

Ruby qoutes, . Ruby.

+2

escape- \, . ,

, "", :

name = 'world'
puts "Hello #{name}" # => "Hello world"

escape-:

puts 'Hello\nworld'       # => "Hello\nworld"
puts "Hello\nworld"       # => "Hello
                                world"
+2

Literals Ruby.

, . , %Q/.../ %Q/.../ .

+2

Ruby , , :

>> 'foo'
=> "foo"
>> 'foo' + 'bar'
=> "foobar"

. , , .

, , Ruby . :

>> '#{foo} bar'
=> "\#{foo} bar"

, , , #.

, .

+1

, escape-, .

:

name = "Mike"
puts "Hello #{name} \n How are you?"

The above ruby ​​code with string interpolation will interpolate a variable with a name namethat is written inside the brackets with its original value, which is equal to Mike. And he will also print a line. How are you? on a separate line, since we have already placed the escape sequence there.

Output:

Hello Mike 
  How are you?

If you do the same thing with single quotes, it will treat the entire string as text, and it will print, since it also includes an escape sequence.

name = Mike'
puts 'Hello #{name} \n How are you'?

Output:

Hello #{name} \n How are you?
0
source

All Articles