Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between '%{}', '%Q{}', '%q{}' in ruby string delimiters

Tags:

string

ruby

I was going through an online tutorial on ruby and found this "General Delimited Strings",

%{a word}  # => "a word" %Q{a word} # => "a word" %q{a word} # equivalent to single quoted version. 

so i tried it on irb and this is what i see

2.0.0p247 :025 > %Q(hi)  => "hi"  2.0.0p247 :026 > %q(the)  => "the"  2.0.0p247 :027 > %q(th"e)  => "th\"e"  2.0.0p247 :028 > %q(th'e)  => "th'e"  2.0.0p247 :029 > %Q(h'i)  => "h'i"  2.0.0p247 :030 > %Q(h"i)  => "h\"i" 

Both %q and %Q behave the same and takes string in double quotes. Anybody know what exactly the use of these 2 if we can use %{} to get the same output.

like image 384
Sonu Oommen Avatar asked Nov 05 '13 05:11

Sonu Oommen


People also ask

What is the difference between symbol and string in Ruby?

symbol is immutable and string is mutable.

What does %I mean in Ruby?

The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.

What does :: mean in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.


2 Answers

Here is some hints about them Ruby_Programming - The % Notation:

%Q[ ] - Interpolated String (default)

%q[ ] - Non-interpolated String (except for \ , [ and ])

Example :

x = "hi" p %Q[#{x} Ram!] #= > "hi Ram!" p %q[#{x} Ram!] #= > "\#{x} Ram!" p %Q[th\e] #= > "th\e" p %q[th\e] #= > "th\\e" # notice the \\ with %q[] 

Another good resource Percent Strings

Besides %(...) which creates a String, The % may create other types of object. As with strings, an uppercase letter allows interpolation and escaped characters while a lowercase letter disables them.

like image 101
Arup Rakshit Avatar answered Nov 11 '22 08:11

Arup Rakshit


%q(no interpolation)

%Q(interpolation and backslashes)

%(interpolation and backslashes)

Example

$ str = 'sushant'  $ %q[#{str} "mane"]  => "\#{str} \"mane\""  $ %Q[#{str} "mane"]  => "sushant \"mane\""  $ %[#{str} "mane"]  => "sushant \"mane\"" 
like image 22
Sushant Mane Avatar answered Nov 11 '22 08:11

Sushant Mane