text
stringlengths 0
444
|
|---|
first, second = multi_return
|
# good - use with splat
|
first, *list = [1, 2, 3, 4] # first => 1, list => [2, 3, 4]
|
hello_array = *'Hello' # => ["Hello"]
|
a = *(1..3) # => [1, 2, 3]
|
----
|
=== Values Swapping [[values-swapping]]
|
Use parallel assignment when swapping 2 values.
|
[source,ruby]
|
----
|
# bad
|
tmp = x
|
x = y
|
y = tmp
|
# good
|
x, y = y, x
|
----
|
=== Dealing with Trailing Underscore Variables in Destructuring Assignment [[trailing-underscore-variables]]
|
Avoid the use of unnecessary trailing underscore variables during
|
parallel assignment. Named underscore variables are to be preferred over
|
underscore variables because of the context that they provide.
|
Trailing underscore variables are necessary when there is a splat variable
|
defined on the left side of the assignment, and the splat variable is
|
not an underscore.
|
[source,ruby]
|
----
|
# bad
|
foo = 'one,two,three,four,five'
|
# Unnecessary assignment that does not provide useful information
|
first, second, _ = foo.split(',')
|
first, _, _ = foo.split(',')
|
first, *_ = foo.split(',')
|
# good
|
foo = 'one,two,three,four,five'
|
# The underscores are needed to show that you want all elements
|
# except for the last number of underscore elements
|
*beginning, _ = foo.split(',')
|
*beginning, something, _ = foo.split(',')
|
a, = foo.split(',')
|
a, b, = foo.split(',')
|
# Unnecessary assignment to an unused variable, but the assignment
|
# provides us with useful information.
|
first, _second = foo.split(',')
|
first, _second, = foo.split(',')
|
first, *_ending = foo.split(',')
|
----
|
=== Self-assignment [[self-assignment]]
|
Use shorthand self assignment operators whenever applicable.
|
[source,ruby]
|
----
|
# bad
|
x = x + y
|
x = x * y
|
x = x**y
|
x = x / y
|
x = x || y
|
x = x && y
|
# good
|
x += y
|
x *= y
|
x **= y
|
x /= y
|
x ||= y
|
x &&= y
|
----
|
=== Conditional Variable Initialization Shorthand [[double-pipe-for-uninit]]
|
Use `||=` to initialize variables only if they're not already initialized.
|
[source,ruby]
|
----
|
# bad
|
name = name ? name : 'Bozhidar'
|
# bad
|
name = 'Bozhidar' unless name
|
# good - set name to 'Bozhidar', only if it's nil or false
|
name ||= 'Bozhidar'
|
----
|
[WARNING]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.