text
stringlengths 0
444
|
|---|
end
|
----
|
===== Non-Declarative Methods That Have "keyword" Status in Ruby [[method-invocation-parens-non-declarative-keyword]][[method-call-parens-non-declarative-keyword]]
|
For non-declarative methods with "keyword" status (e.g., various `Kernel` instance methods), two styles are considered acceptable.
|
By far the most popular style is to omit parentheses.
|
Rationale: The code reads better, and method calls look more like keywords.
|
A less-popular style, but still acceptable, is to include parentheses.
|
Rationale: The methods have ordinary semantics, so why treat them differently, and it's easier to achieve a uniform style by not worrying about which methods have "keyword" status.
|
Whichever one you pick, apply it consistently.
|
[source,ruby]
|
----
|
# good (most popular)
|
puts temperance.age
|
system 'ls'
|
exit 1
|
# also good (less popular)
|
puts(temperance.age)
|
system('ls')
|
exit(1)
|
----
|
==== Using `super` with Arguments [[super-with-args]]
|
Always use parentheses when calling `super` with arguments:
|
[source,ruby]
|
----
|
# bad
|
super name, age
|
# good
|
super(name, age)
|
----
|
IMPORTANT: When calling `super` without arguments, `super` and `super()` mean different things. Decide what is appropriate for your usage.
|
=== Too Many Params [[too-many-params]]
|
Avoid parameter lists longer than three or four parameters.
|
=== Optional Arguments [[optional-arguments]]
|
Define optional arguments at the end of the list of arguments.
|
Ruby has some unexpected results when calling methods that have optional arguments at the front of the list.
|
[source,ruby]
|
----
|
# bad
|
def some_method(a = 1, b = 2, c, d)
|
puts "#{a}, #{b}, #{c}, #{d}"
|
end
|
some_method('w', 'x') # => '1, 2, w, x'
|
some_method('w', 'x', 'y') # => 'w, 2, x, y'
|
some_method('w', 'x', 'y', 'z') # => 'w, x, y, z'
|
# good
|
def some_method(c, d, a = 1, b = 2)
|
puts "#{a}, #{b}, #{c}, #{d}"
|
end
|
some_method('w', 'x') # => '1, 2, w, x'
|
some_method('w', 'x', 'y') # => 'y, 2, w, x'
|
some_method('w', 'x', 'y', 'z') # => 'y, z, w, x'
|
----
|
=== Keyword Arguments Order
|
Put required keyword arguments before optional keyword arguments. Otherwise, it's much harder to spot optional arguments there, if they're hidden somewhere in the middle.
|
[source,ruby]
|
----
|
# bad
|
def some_method(foo: false, bar:, baz: 10)
|
# body omitted
|
end
|
# good
|
def some_method(foo:, bar: false, baz: 10)
|
# body omitted
|
end
|
----
|
=== Boolean Keyword Arguments [[boolean-keyword-arguments]]
|
Use keyword arguments when passing a boolean argument to a method.
|
[source,ruby]
|
----
|
# bad
|
def some_method(bar = false)
|
puts bar
|
end
|
# bad - common hack before keyword args were introduced
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.