zed.0xff.me

Advanced Ruby: percent-literals

most used %-literals:

% code result description
%q %q(all `quotes` 'are' "ok") "all `quotes` 'are' \"ok\"" creates String
%r %r(i_am/a/regexp) /i_am\/a\/regexp/ creates Regexp
%w %w(abc def ghi) ["abc", "def", "ghi"] splits string into Array
%x %x(ls -a /tmp) ".\n..\nfile1\nfile2\n" alias of `cmd`

highlighted

1
2
3
4
5
6
7
%q(all `quotes` 'are' "ok") => "all `quotes` 'are' \"ok\""

%r(i_am/a/regexp)           => /i_am\/a\/regexp/

%w(abc def ghi)             => ["abc", "def", "ghi"]

%x(ls -a /tmp)              => ".\n..\nfile1\nfile2\n"

interpolation

1
2
3
4
5
6
7
8
9
10
11
# lowercase 'w': as-is
%w'a #{2+2} b' => ["a", "\#{2+2}", "b"] 

# uppercase 'W': interpolate
%W'a #{2+2} b' => ["a", "4", "b"] 

# lowercase 'q': as-is
%q'a #{2+2} b' => "a \#{2+2} b" 

# uppercase 'Q': interpolate
%Q'a #{2+2} b' => "a 4 b" 

other %-literals

1
2
3
4
5
6
7
8
# %s: convert to symbol
%s'foo' => :foo 

# %i: convert to array of symbols - not released yet, will be in Ruby 2.0 ?
%i'foo bar baz' => [:foo, :bar, :baz]

# '%' w/o any letter - alias for %Q
%'a #{2+2} b' => "a 4 b"
  1. Gravatar tlokq06dzk says:

    <a href="http://6a40f104b2rxreq4l.com">3mulm7mi9n</a>
    <a href="http://1m2g3bybs.com">nn5j5obcnd</a>
    <a href="http://rlsvf3i9c5683kr2637u.com">hev35ro1dk</a>
    http://mk84k8n906fhh.com
    http://k54ra5jq4.com
    http://fwuzt2ljsrth6q8.com
    [url=http://564m42w3fj3nz7uyh.com]vow83onio2[/url]
    [url=http://ebaq2od2.com]bbhp024m97[/url]
    [url=http://cl4xbgxd1rrfwfdz9gv.com]fmvctav29g[/url]

  2. Gravatar cqy92g52du says:

    <a href="http://nlurmt7yhkzg9akdohmb.com">98nur92k9l</a>
    <a href="http://8bipxbsil9makc.com">0rda1pi7kh</a>
    <a href="http://7mr0db5vu0f.com">keeaej7bwu</a>
    http://gcvru5lq98za85iyuyu.com
    http://5y4xj7c55c8om0w.com
    http://1ci5um7zks.com
    [url=http://xs8fhm9jpjvyzd.com]r1yavk76yd[/url]
    [url=http://vn6c6tqri.com]bwm8bftr87[/url]
    [url=http://czohvargo35ohgq8au.com]ix6i7qcz7j[/url]

Post a comment


(lesstile enabled - surround code blocks with ---)