Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby single and double quotes

Tags:

ruby

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.

like image 413
anakin Avatar asked Nov 28 '13 19:11

anakin


1 Answers

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"
like image 50
sethvargo Avatar answered Sep 21 '22 22:09

sethvargo