Featured image

Percent literals in Ruby are one of the most powerful and awesome features of the language, with no direct, equally flexible equivalents in popular modern languages like Python, Java, Rust, or Go.

In short, the syntax works like this: it starts with a % symbol, followed by a letter indicating the result type, and the literal itself enclosed between delimiter characters. Usually, an uppercase letter enables interpolation (and escape sequence processing), while a lowercase letter treats the body literally with %r and %x being exceptions that still interpolate even in lowercase.

Their standout feature is that you can choose virtually any non-alphanumeric character as a delimiter, rather than being limited to paired brackets like <>, (), [], or {}. For example, you can write a string like this:

s = %q*Ruby - one of the best programming languages for web projects.*

If you need to use the delimiter character itself inside the literal, simply escape it with a backslash:

s = %q*Ruby - one of the best \*programming languages\* for web projects.*

Do you use percent literals in your projects? What unusual delimiters have you seen or used in your code?

%Q(Current Ruby version is #{RUBY_VERSION})
# => "Current Ruby version is 4.0.10"

%q(Current Ruby version is #{RUBY_VERSION})
# => "Current Ruby version is \#{RUBY_VERSION}"

%s(symbol is not interpolated #{1 + 1})
# => :"symbol is not interpolated \#{1 + 1}"

%w<Ruby Python Java Golang Rust Visual\ Basic>
# => ["Ruby", "Python", "Java", "Golang", "Rust", "Visual Basic"]

%I[ruby2.1 ruby2.7 ruby3.1 ruby3.3 ruby#{RUBY_VERSION[/\A\d+\.\d+/]}]
# => [:"ruby2.1", :"ruby2.7", :"ruby3.1", :"ruby3.3", :"ruby4.0"]

%r![a-z0-#{2+2}]!i
# => /[a-z0-4]/i

%x$echo -n #{2 + 2}$
# => "4"