text stringlengths 0 444 |
|---|
[source,ruby] |
---- |
# bad |
# frozen_string_literal: true |
# Some documentation for Person |
class Person |
# Some code |
end |
# good |
# frozen_string_literal: true |
# Some documentation for Person |
class Person |
# Some code |
end |
---- |
== Collections |
=== Literal Array and Hash [[literal-array-hash]] |
Prefer literal array and hash creation notation (unless you need to pass parameters to their constructors, that is). |
[source,ruby] |
---- |
# bad |
arr = Array.new |
hash = Hash.new |
# good |
arr = [] |
arr = Array.new(10) |
hash = {} |
hash = Hash.new(0) |
---- |
=== `%w` [[percent-w]] |
Prefer `%w` to the literal array syntax when you need an array of words (non-empty strings without spaces and special characters in them). |
Apply this rule only to arrays with two or more elements. |
[source,ruby] |
---- |
# bad |
STATES = ['draft', 'open', 'closed'] |
# good |
STATES = %w[draft open closed] |
---- |
=== `%i` [[percent-i]] |
Prefer `%i` to the literal array syntax when you need an array of symbols (and you don't need to maintain Ruby 1.9 compatibility). |
Apply this rule only to arrays with two or more elements. |
[source,ruby] |
---- |
# bad |
STATES = [:draft, :open, :closed] |
# good |
STATES = %i[draft open closed] |
---- |
=== No Trailing Array Commas [[no-trailing-array-commas]] |
Avoid comma after the last item of an `Array` or `Hash` literal, especially when the items are not on separate lines. |
[source,ruby] |
---- |
# bad - easier to move/add/remove items, but still not preferred |
VALUES = [ |
1001, |
2020, |
3333, |
] |
# bad |
VALUES = [1001, 2020, 3333, ] |
# good |
VALUES = [1001, 2020, 3333] |
---- |
=== No Gappy Arrays [[no-gappy-arrays]] |
Avoid the creation of huge gaps in arrays. |
[source,ruby] |
---- |
arr = [] |
arr[100] = 1 # now you have an array with lots of nils |
---- |
=== `first` and `last` [[first-and-last]] |
When accessing the first or last element from an array, prefer `first` or `last` over `[0]` or `[-1]`. |
=== Set vs Array [[set-vs-array]] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.