text stringlengths 0 444 |
|---|
paragraphs.each do |paragraph| |
html += "<p>#{paragraph}</p>" |
end |
# good and also fast |
html = '' |
html << '<h1>Page title</h1>' |
paragraphs.each do |paragraph| |
html << "<p>#{paragraph}</p>" |
end |
---- |
=== Don't Abuse `gsub` [[dont-abuse-gsub]] |
Don't use `String#gsub` in scenarios in which you can use a faster and more specialized alternative. |
[source,ruby] |
---- |
url = 'http://example.com' |
str = 'lisp-case-rules' |
# bad |
url.gsub('http://', 'https://') |
str.gsub('-', '_') |
# good |
url.sub('http://', 'https://') |
str.tr('-', '_') |
---- |
=== `String#chars` [[string-chars]] |
Prefer the use of `String#chars` over `String#split` with empty string or regexp literal argument. |
NOTE: These cases have the same behavior since Ruby 2.0. |
[source,ruby] |
---- |
# bad |
string.split(//) |
string.split('') |
# good |
string.chars |
---- |
=== `sprintf` [[sprintf]] |
Prefer the use of `sprintf` and its alias `format` over the fairly cryptic `String#%` method. |
[source,ruby] |
---- |
# bad |
'%d %d' % [20, 10] |
# => '20 10' |
# good |
sprintf('%d %d', 20, 10) |
# => '20 10' |
# good |
sprintf('%<first>d %<second>d', first: 20, second: 10) |
# => '20 10' |
format('%d %d', 20, 10) |
# => '20 10' |
# good |
format('%<first>d %<second>d', first: 20, second: 10) |
# => '20 10' |
---- |
=== Named Format Tokens [[named-format-tokens]] |
When using named format string tokens, favor `%<name>s` over `%{name}` because it encodes information about the type of the value. |
[source,ruby] |
---- |
# bad |
format('Hello, %{name}', name: 'John') |
# good |
format('Hello, %<name>s', name: 'John') |
---- |
=== Long Strings [[heredoc-long-strings]] |
Break long strings into multiple lines but don't concatenate them with `+`. |
If you want to add newlines, use heredoc. Otherwise use `\`: |
[source,ruby] |
---- |
# bad |
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. " + |
"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, " + |
"when an unknown printer took a galley of type and scrambled it to make a type specimen book." |
# good |
<<~LOREM |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.