Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does %{} do in Ruby?

Tags:

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?

like image 242
user5243421 Avatar asked Mar 14 '11 19:03

user5243421


People also ask

What does << mean in Ruby?

In ruby '<<' operator is basically used for: Appending a value in the array (at last position) [2, 4, 6] << 8 It will give [2, 4, 6, 8] It also used for some active record operations in ruby.

What does * do in Ruby?

The * is the splat operator. It expands an Array into a list of arguments, in this case a list of arguments to the Hash. [] method. (To be more precise, it expands any object that responds to to_ary / to_a , or to_a in Ruby 1.9.)


1 Answers

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

like image 91
jpgeek Avatar answered Sep 20 '22 07:09

jpgeek