Sonntag, 26. Oktober 2014

Take a look at Ruby percentages

There are some Ruby %-notations which emerge as nice shortcuts. Those literals are Perl inspired.
Please note, that indeed all non-alpha-numeric delimiters are allowed, but it is highly recommended to use bracket delimiters for readability and unescaping reasons, like:
  1. ()
  2. []
  3. {}
  4. <>

1. Non-interpolated String

allows unescaping and string notation:
%q(Ruby string (syntax) is "pretty" flexible)
=> "Ruby string (syntax) is \"pretty\" flexible"
Please compare with the String result.

2. Interpolated String

allows flexible interpolation:
choosen_language = "Ruby"
%Q(#{choosen_language} string (syntax) is "pretty" flexible)
=> "Ruby string (syntax) is \"pretty\" flexible"
and there is also an even shorter literal. % (percentage) alone is the default for an interpolated String:
choosen_language = "Ruby"
%(#{choosen_language} string (syntax) is "pretty" flexible)
=> "Ruby string (syntax) is \"pretty\" flexible"

3. Non-interpolated Symbol

is maybe unusual:
=> :ruby
But dealing with arbitrary characters like spaces and dashes also works:
%s(ruby is awesome)
=> :"ruby is awesome"
and is more concise and idiomatic than:
"ruby is awesome".to_sym
=> :"ruby is awesome"

4. Non-interpolated String Array

is already quite popular:
%w(Ruby Python Clojure)
=> ["Ruby", "Python", "Clojure"]
The Array elements are separated by whitespace.

5. Interpolated String Array

is more flexible:
choosen_language = "Ruby"
%W(#{choosen_language} Python Clojure)
=> ["Ruby", "Python", "Clojure"]
The Array elements also are separated by whitespace.

6. Non-interpolated Symbol Array

maybe is less known but analog to its String companion:
%i(ruby python clojure)
=> [:ruby, :python, :clojure]

7. Interpolated Symbol Array

is also equivalent to its String mate:
choosen_language = "ruby"
%I(#{choosen_language} python clojure)
=> [:ruby, :python, :clojure]

8. Interpolated shell command

is pretty helpful for shell scripting:
language = "ruby"
%x(#{language} --version)
=> "ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-linux]\n"
language = "nodejs"
%x(#{language} --version)
=> "v0.10.32\n"
Although there are also other Ruby shell scripting approaches (Please read Tell shell scripting apart in Ruby!)

9. Interpolated regular expression

can be used with flags after the closing delimiter
disliked_language = "Java"
string = %Q(#{disliked_language} helps to solve my problems.)
regexp = /#{disliked_language}/i
string.gsub(regexp, 'Ruby')
The literal briefing:
Literal Meaning
%qNon-interplated String
%QInterpolated String
%sNon-interpolated Symbol
%wNon-interpolated String Array
%WInterpolated String Array
%iNon-interpolated Symbol Array
%IInterpolated Symbol Array
%xInterpolated Shell command
%rInterpolated regular expression

Further articles of interest:

Supported by Ruby 2.1.1