Difference between '%{}', '%Q{}', '%q{}' in ruby string delimiters
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.
Whats the difference between %Q and %{} in ruby?
Jim Hoskins clears it up.
%Q is the equivalent to a double-quoted ruby string. #{expression} evaluation works just like in double-quoted strings, even if you use %Q{} as your delimiter!
You can also leave off the Q and it will have the same functionality. I recommend leaving the Q in to be more clear.
What is the use case for Ruby's %q / %Q quoting methods?
They're extraordinarily useful for escaping HTML with JavaScript in it where you've already "run out" of quoting methods:
link = %q[<a href="javascript:method('call')">link</a>]
I've also found them to be very useful when working with multi-line SQL statements:
execute(%Q[
INSERT INTO table_a (column_a)
SELECT value
FROM table_b
WHERE key='value'
])
The advantage there is you don't need to pay attention to the type of quoting used within your query. It will work with either single, double, or both. They're also a lot less fuss than the HEREDOC style method.
Ruby provides other convenience methods like this such as %r
which can construct regular expressions. That avoids slash-itis when trying to write one that handles stuff like http://
that would otherwise have to be escaped.
What does %w(array) mean?
%w(foo bar)
is a shortcut for ["foo", "bar"]
. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.
Where in the Ruby language is %q, %w, etc., defined?
They are “hard coded” in the parser; see
- parse.y from the tip of Ruby 1.9.2 or
- parse.y from the tip of Ruby 1.8.7.
The easiest way to find the code in question is to look for the second occurrence of str_sword
(Single-quoted WORDs). All the “delimited input” syntax is defined there: %Q
, %q
, %W
, %w
, %x
, %r
, and %s
(both versions referenced above define the same set of delimited input markers).
can you use the ruby percent notation for strings with interpolation?
Try %Q
instead of %q
. For instance:
catchphrase = 'wubba lubba dub dub'
%Q[My new catchphrase is "#{catchphrase}"] #=> "My new catchphrase is \"wubba lubba dub dub\""
Which style of Ruby string quoting do you favour?
Don't use double quotes if you have to escape them. And don't fall in "single vs double quotes" trap. Ruby has excellent support for arbitrary delimiters for string literals:
Mirror of Site - https://web.archive.org/web/20160310224440/http://rors.org/2008/10/26/dont-escape-in-strings
Original Site -
http://rors.org/2008/10/26/dont-escape-in-strings
Semantic differences between percent literals and herdocs in Ruby?
There isn't really a semantic difference, and it doesn't have to do with multiline strings either. All strings can be multiline in Ruby. These are all the same string:
'a
b
'
"a
b
"
%Q{a
b
}
<<-heredoc
a
b
heredoc
The question of which to use is decided by whether you need interpolation and the convenience of escaping characters. For example:
- Do you need interpolation? If not then
''
or%q()
- Will there be lots of quote characters to escape? Then use
%Q()
- Do you want to write a lot of text without thinking about escaping characters? Use heredocs.
What does %i or %I do in Ruby?
%i[ ] # Non-interpolated Array of symbols, separated by whitespace
%I[ ] # Interpolated Array of symbols, separated by whitespace
The second link from my search results http://ruby.zigzo.com/2014/08/21/rubys-notation/
Examples in IRB:
%i[ test ]
# => [:test]
str = "other"
%I[ test_#{str} ]
# => [:test_other]
Related Topics
Accessing Objects Memory Address in Ruby
How to Merge Two Hashes with No New Keys
Rake Assets:Precompile Attempting to Connect to Database
How to Compile Ruby with Rvm on a Low Memory System
Getting Typed Results from Activerecord Raw SQL
How to Add MAC-Specific Gems to Bundle on MAC But Not on Linux
Differences Between Proc and Lambda
Failed to Build Gem Native Extension
Why Are My Bigdecimal Objects Initialized with Unexpected Rounding Errors
How to Share the Factories That I Have in a Gem and Use It in Other Project
How to Wrap the Invocation of a Ruby Method by Including a Module
Rails 3. How to Add a Helper That Activeadmin Will Use
What's the Difference Between the Build and Create Methods in Factorygirl
Does Using ":Platforms =>" in Your Gemfile Work
Homebrew Install: Failed During: Git Fetch Origin Master:Refs/Remotes/Origin/Master -N --Depth=1