text
stringlengths
0
444
foo(<<~SQL
select foo from bar
SQL
)
# good
foo(<<~SQL)
select foo from bar
SQL
----
== Date & Time
=== `Time.now` [[time-now]]
Prefer `Time.now` over `Time.new` when retrieving the current system time.
=== No `DateTime` [[no-datetime]]
Don't use `DateTime` unless you need to account for historical calendar reform - and if you do, explicitly specify the `start` argument to clearly state your intentions.
[source,ruby]
----
# bad - uses DateTime for current time
DateTime.now
# good - uses Time for current time
Time.now
# bad - uses DateTime for modern date
DateTime.iso8601('2016-06-29')
# good - uses Date for modern date
Date.iso8601('2016-06-29')
# good - uses DateTime with start argument for historical date
DateTime.iso8601('1751-04-23', Date::ENGLAND)
----
== Regular Expressions
[quote, Jamie Zawinski]
____
Some people, when confronted with a problem, think
"I know, I'll use regular expressions." Now they have two problems.
____
=== Plain Text Search [[no-regexp-for-plaintext]]
Don't use regular expressions if you just need plain text search in string.
[source,ruby]
----
foo = 'I am an example string'
# bad - using a regular expression is an overkill here
foo =~ /example/
# good
foo['example']
----
=== Using Regular Expressions as String Indexes [[regexp-string-index]]
For simple constructions you can use regexp directly through string index.
[source,ruby]
----
match = string[/regexp/] # get content of matched regexp
first_group = string[/text(grp)/, 1] # get content of captured group
string[/text (grp)/, 1] = 'replace' # string => 'text replace'
----
=== Prefer Non-capturing Groups [[non-capturing-regexp]]
Use non-capturing groups when you don't use the captured result.
[source,ruby]
----
# bad
/(first|second)/
# good
/(?:first|second)/
----
=== Do not mix named and numbered captures [[do-not-mix-named-and-numbered-captures]]
Do not mix named captures and numbered captures in a Regexp literal.
Because numbered capture is ignored if they're mixed.
[source,ruby]
----
# bad - There is no way to access `(BAR)` capturing.
m = /(?<foo>FOO)(BAR)/.match('FOOBAR')
p m[:foo] # => "FOO"
p m[1] # => "FOO"
p m[2] # => nil - not "BAR"
# good - Both captures are accessible with names.