What does %q do?

J

John Feminella

%q{abc} is equivalent to writing "abc". It's most useful when you have
a string literal that contains a lot of characters you'd need to
escape. Compare:

"Gaba Luschi asked the ruby-talk list, \"What does %q do?\""

vs.

%q{Gaba Luschi asked the ruby-talk list, "What does %q do?"}

And note they're equal:
a = %q{Gaba Luschi asked the ruby-talk list, "What does %q do?"}
b = "Gaba Luschi asked the ruby-talk list, \"What does %q do?\""
=> true

~ jf
--
John Feminella
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: http://stackoverflow.com/users/75170/
 
J

John Feminella

Whoops, small typo:
%q{abc} is equivalent to writing "abc".

should read:
%q{abc} is equivalent to writing 'abc' (single quotes).

By contrast, %Q{abc} is equivalent to writing "abc" (double quotes).
You can see the difference when you try to substitute variables:
f =3D "apple"
%q{#{f}} =3D> "\#{f}"
%Q{#{f}}
=3D> "apple"

~ jf
--
John Feminella
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: http://stackoverflow.com/users/75170/



%q{abc} is equivalent to writing "abc". It's most useful when you have
a string literal that contains a lot of characters you'd need to
escape. Compare:

"Gaba Luschi asked the ruby-talk list, \"What does %q do?\""

vs.

%q{Gaba Luschi asked the ruby-talk list, "What does %q do?"}

And note they're equal:
a =3D %q{Gaba Luschi asked the ruby-talk list, "What does %q do?"}
b =3D "Gaba Luschi asked the ruby-talk list, \"What does %q do?\""
a =3D=3D b
=C2=A0=3D> true

~ jf
--
John Feminella
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: http://stackoverflow.com/users/75170/



 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

Also, lowercase q is like single quotes, but uppercase Q is like double
quotes:

%q(1#{1+1}3) # => "1\#{1+1}3"
%Q(1#{1+1}3) # => "123"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,229
Latest member
GloryAngul

Latest Threads

Top