In Ruby, besides %w
which is used to create an array of strings, there are several other notations that use the %
character followed by a letter. Here are some of them:
%q
or %Q
: These notations are used to create a single-quoted or double-quoted string, respectively. They are useful when you have a string that contains many special characters and you want to avoid escaping them. For example:
main.rb131 chars3 lines
%r
: This notation is used to create a regular expression. It allows you to define a regular expression pattern without the need for explicitly using the Regexp.new
constructor. For example:
main.rb87 chars3 lines
%s
: This notation is used to create a symbol, which is a lightweight constant in Ruby. It is similar to a string but immutable and unique. For example:
main.rb44 chars3 lines
%i
or %I
: These notations are used to create an array of symbols. %i
creates symbols without interpolation, while %I
allows for interpolation. For example:
main.rb100 chars4 lines
These notations provide a convenient way to create certain types of objects in Ruby. They are especially helpful when you have strings or patterns that contain characters that would normally require escaping.
gistlibby LogSnag