Read more

Ruby's percent notation can do more than strings

Michael Leimstädtner
October 23, 2018Software engineer at makandra GmbH

Percent Notation

We already know that that we can create strings using the percent notation:

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

%{<foo="bar's ton">} is perfectly fine Ruby.

Modifier

But there is more. The curly brackets ({}) are interchangable with most unicode characters (e.g. square brackets[]).
Furthermore, you can add a " modifier Show archive.org snapshot " to the percent notation to control the return type of the expression:

%s	Symbol
%i	Array of Symbols
%q	String
%w	Array of Strings
%r	Regular Expression
%x	Backtick (capture subshell result)*

Examples:

%i[foo bar] 
=> [:foo, :bar]

%q[foo bar] 
=> "foo bar"

Interpolation

To interpolate a dynamic value, swap the modifier with the corresponding uppercase letter:

%I[a list of #{'inter'}polated symbols]
=> [:a, :list, :of, :interpolated, :symbols]

*Please keep in mind that we'd prefer Open3 for shell commands.

Posted by Michael Leimstädtner to makandra dev (2018-10-23 15:03)