boo-urns
boo-urns

Reputation: 10376

What does %{} do in Ruby?

In Matt's post about drying up cucumber tests, 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?

Upvotes: 39

Views: 17695

Answers (3)

jpgeek
jpgeek

Reputation: 5281

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

Upvotes: 36

Michael Kohl
Michael Kohl

Reputation: 66837

  1. "Percent literals" is usually a good way to google some information:

  2. #{} is called "string interpolation".

Upvotes: 13

Steven
Steven

Reputation: 18014

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.

Upvotes: 12

Related Questions