Percent literals: % (the one for strings)
Earlier this week, we covered both the %w and %r percent literals. The last percent literal I wanted to mention is the bare % followed by a delimiter of your choice. This is useful for creating strings with interpolation support without needing to escape quotes:
name = "Elwin"
attribute = %(name: "#{name}")
# => "name: \"Elwin\""
markdown = %(
# Hello, #{name}!
Here's how you write Hello World in Ruby:
```ruby
puts "Hello, world!"
```
).strip
# => "# Hello, Elwin!\n\nHere's how you write Hello World in Ruby:\n\n```..."
const name = "Elwin";
const attribute = `name: "${name}"`;
// => "name: \"Elwin\""
const markdown = `
# Hello, ${name}!
Here's how you write Hello World in Ruby:
\`\`\`ruby
puts "Hello, world!"
\`\`\`
`.trim();
// => "# Hello, Elwin!\n\nHere's how you write Hello World in Ruby:\n\n```..."
While the backtick syntax for template literals has improved the situation for JavaScript considerably compared to the old days, the markdown example above exposes its Achilles' heel: the need to escape backticks. With % in Ruby, we can choose any delimiter we want, so we can avoid the need to escape pretty much anything.
% is actually a shorthand for %Q, the percent literal for double-quoted strings. If you want to create a single-quoted string without interpolation support, you can use %q instead. But considering I've never found a reason to use it in my 20 years of Ruby programming, chances are you'll be fine just sticking with % for all your string needs.
History
Just like with the other percent literals, %q, %Q and % have been around since Ruby's inception, and again were inspired by Perl. In Perl, you can use q and qq followed by a delimiter of your choice to create single-quoted and double-quoted strings, respectively.