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.
%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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With