text stringlengths 0 444 |
|---|
[source,ruby] |
---- |
require 'tempfile' |
# bad |
def with_tmp_dir |
Dir.mktmpdir do |tmp_dir| |
Dir.chdir(tmp_dir) { |dir| yield dir } # block just passes arguments |
end |
end |
# good |
def with_tmp_dir(&block) |
Dir.mktmpdir do |tmp_dir| |
Dir.chdir(tmp_dir, &block) |
end |
end |
with_tmp_dir do |dir| |
puts "dir is accessible as a parameter and pwd is set: #{dir}" |
end |
---- |
=== Trailing Comma in Block Parameters [[no-trailing-parameters-comma]] |
Avoid comma after the last parameter in a block, except in cases where only a single argument is present and its removal would affect functionality (for instance, array destructuring). |
[source,ruby] |
---- |
# bad - easier to move/add/remove parameters, but still not preferred |
[[1, 2, 3], [4, 5, 6]].each do |a, b, c,| |
a + b + c |
end |
# good |
[[1, 2, 3], [4, 5, 6]].each do |a, b, c| |
a + b + c |
end |
# bad |
[[1, 2, 3], [4, 5, 6]].each { |a, b, c,| a + b + c } |
# good |
[[1, 2, 3], [4, 5, 6]].each { |a, b, c| a + b + c } |
# good - this comma is meaningful for array destructuring |
[[1, 2, 3], [4, 5, 6]].map { |a,| a } |
---- |
=== Nested Method Definitions [[no-nested-methods]] |
Do not use nested method definitions, use lambda instead. |
Nested method definitions actually produce methods in the same scope (e.g. class) as the outer method. |
Furthermore, the "nested method" will be redefined every time the method containing its definition is called. |
[source,ruby] |
---- |
# bad |
def foo(x) |
def bar(y) |
# body omitted |
end |
bar(x) |
end |
# good - the same as the previous, but no bar redefinition on every foo call |
def bar(y) |
# body omitted |
end |
def foo(x) |
bar(x) |
end |
# also good |
def foo(x) |
bar = ->(y) { ... } |
bar.call(x) |
end |
---- |
=== Multi-line Lambda Definition [[lambda-multi-line]] |
Use the new lambda literal syntax for single-line body blocks. |
Use the `lambda` method for multi-line blocks. |
[source,ruby] |
---- |
# bad |
l = lambda { |a, b| a + b } |
l.call(1, 2) |
# correct, but looks extremely awkward |
l = ->(a, b) do |
tmp = a * 7 |
tmp * b / 50 |
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.