Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've recently been coding in Ruby and have come from Python, where single and double quotes made no difference to how the code worked as far as I know.

I moved to Ruby to see how it worked, and to investigate the similarities between Ruby and Python.

I was using single-quoted strings once and noticed this:

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

It returned '#{hello} world!' rather than 'hello world!'.

After noticing this I tried double quotes and the problem was fixed. Now I'm not sure why that is.

Do single and double quotes change this or is it because of my editor (Sublime text 3)? I'm also using Ruby version 2.0 if it works differently in previous versions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

In Ruby, double quotes are interpolated, meaning the code in #{} is evaluated as Ruby. Single quotes are treated as literals (meaning the code isn't evaluated).

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

For some extra-special magic, Ruby also offers another way to create strings:

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

For example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...