Search code examples
ruby-on-railsruby

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.


Solution

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

    Documentation