Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby %() vs. ""

I notice some people use %(string here) instead of a simple use of double quotes as "string here". Is there any reason for this? When I use the first layout, I usually make an array such as %w(my array here) so I don't have to use quotes and commas.

Is there a hidden rule I am unaware of? I can't imagine why I would do this:

a = %(some string here)

instead of

b = "some string here"

The latter just seems more clearly written.

like image 795
dingalingchickenwiing Avatar asked Feb 24 '14 16:02

dingalingchickenwiing


People also ask

What does %w mean Ruby?

%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.

How do you add a double quote to a string in Ruby?

Answer 51d2afb1282ae33a990093c5. Single-quoted and double-quoted strings are (almost) equivalent in Ruby. Of course, you have to escape \' inside single-quoted strings and \" inside double-quoted strings.

What is a string literal in Ruby?

String literals are simply strings that are created using Ruby's built-in string syntax. This includes those created using double quotes (“), single quotes ('), or the special forms %Q and %q. Traditionally, these forms have all created strings that can be modified.


1 Answers

They are almost equivalent, using %() you don't have to escape the " character inside the string:

s = %(foo "bar" baz)
# => "foo \"bar\" baz"

They are mostly useful when your string is full of double quotes.

like image 142
toro2k Avatar answered Sep 22 '22 19:09

toro2k