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.
symbol is immutable and string is mutable.
The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.
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.
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.
%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\""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With