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" |
Advanced Ruby: break(value) & next(value)
1. break(value)
break
accepts a value that supplies the result of the expression it is “breaking” out of:
1 2 3 4 5 |
result = [1, 2, 3].each do |value| break value * 2 if value.even? end p result # prints 4 |
2. next(value)
next
accepts an argument that can be used the result of the current block iteration:
1 2 3 4 5 6 7 |
result = [1, 2, 3].map do |value| next value if value.even? value * 2 end p result # prints [2, 2, 6] |