What does %{} do in Ruby?
In Matt's post about drying up cucumber test开发者_开发问答s, Aslak suggests the following.
When I have lots of quotes, I prefer this:
Given %{I enter “#{User.first.username}” in “username”}
What is the %{CONTENT}
construct called? Will someone mind referencing it in some documentation? I'm not sure how to go about looking it up.
There's also the stuff about %Q
. Is that equivalent to just %
? What of the curly braces? Can you use square braces? Do they function differently?
Finally, what is the #{<ruby stuff to be evaluated>}
construct called? Is there a reference to that in documentation somewhere, too?
None of the other answers actually answer the question.
This is percent sign notation. The percent sign indicates that the next character is a literal delimiter, and you can use any (non alphanumeric) one you want. For example:
%{stuff}
%[stuff]
%?stuff?
etc. This allows you to put double quotes, single quotes etc into the string without escaping:
%{foo='bar with embedded "baz"'}
returns the literal string: foo='bar with embedded "baz"'
The percent sign can be followed by a letter modifier to determine how the string is interpolated. For example, %Q[ ]
is an interpolated String, %q[ ]
is a non-interpolated String, %i[ ]
is a non-interpolated Array of Symbols etc. So for example:
%i#potato tuna#
returns this array of Symbols:
[:potato, :tuna]
Details are here: Wikibooks
"Percent literals" is usually a good way to google some information:
- http://www.sampierson.com/articles/ruby-percent-literals
- http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation
#{}
is called "string interpolation".
The #{1+1}
is called String Interpolation.
I, and Wikibooks, refer to the %
stuff as just "% notation". Reference here. The %
notation takes any delimiter, so long as it's non alphanumeric. It can also take modifiers (kind of like how regular expressions take options), one of which, interestingly enough, is whether you'll permit #{}
-style string interpolation (this is also enabled by default).
%
then does some special stuff to it, giving that notation some distinct, if a bit cryptic to beginners, terseness. For example %w{hello world}
returns an array ['hello','world']
. %s{hello}
returns a symbol :hello
.
精彩评论