text
stringlengths 0
444
|
|---|
\s
|
(group)
|
(?:alt1|alt2)
|
end
|
/x
|
----
|
=== Comment Complex Regular Expressions [[comment-regexes]]
|
Use `x` modifier for complex regexps.
|
This makes them more readable and you can add some useful comments.
|
[source,ruby]
|
----
|
regexp = /
|
start # some text
|
\s # white space char
|
(group) # first group
|
(?:alt1|alt2) # some alternation
|
end
|
/x
|
----
|
=== Use `gsub` with a Block or a Hash for Complex Replacements [[gsub-blocks]]
|
For complex replacements `sub`/`gsub` can be used with a block or a hash.
|
[source,ruby]
|
----
|
words = 'foo bar'
|
words.sub(/f/, 'f' => 'F') # => 'Foo bar'
|
words.gsub(/\w+/) { |word| word.capitalize } # => 'Foo Bar'
|
----
|
== Percent Literals
|
=== `%q` shorthand [[percent-q-shorthand]]
|
Use `%()` (it's a shorthand for `%Q`) for single-line strings which require both interpolation and embedded double-quotes.
|
For multi-line strings, prefer heredocs.
|
[source,ruby]
|
----
|
# bad (no interpolation needed)
|
%(<div class="text">Some text</div>)
|
# should be '<div class="text">Some text</div>'
|
# bad (no double-quotes)
|
%(This is #{quality} style)
|
# should be "This is #{quality} style"
|
# bad (multiple lines)
|
%(<div>\n<span class="big">#{exclamation}</span>\n</div>)
|
# should be a heredoc.
|
# good (requires interpolation, has quotes, single line)
|
%(<tr><td class="name">#{name}</td>)
|
----
|
=== `%q` [[percent-q]]
|
Avoid `%()` or the equivalent `%q()` unless you have a string with both `'` and `"` in it.
|
Regular string literals are more readable and should be preferred unless a lot of characters would have to be escaped in them.
|
[source,ruby]
|
----
|
# bad
|
name = %q(Bruce Wayne)
|
time = %q(8 o'clock)
|
question = %q("What did you say?")
|
# good
|
name = 'Bruce Wayne'
|
time = "8 o'clock"
|
question = '"What did you say?"'
|
quote = %q(<p class='quote'>"What did you say?"</p>)
|
----
|
=== `%r` [[percent-r]]
|
Use `%r` only for regular expressions matching _at least_ one `/` character.
|
[source,ruby]
|
----
|
# bad
|
%r{\s+}
|
# good
|
%r{^/(.*)$}
|
%r{^/blog/2011/(.*)$}
|
----
|
=== `%x` [[percent-x]]
|
Avoid the use of `%x` unless you're going to execute a command with backquotes in it (which is rather unlikely).
|
[source,ruby]
|
----
|
# bad
|
date = %x(date)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.