text stringlengths 0 444 |
|---|
NOTE: Ruby 3 introduced an alternative syntax for single-line method definitions, that's discussed in the next section |
of the guide. |
[source,ruby] |
---- |
# bad |
def too_much; something; something_else; end |
# okish - notice that the first ; is required |
def no_braces_method; body end |
# okish - notice that the second ; is optional |
def no_braces_method; body; end |
# okish - valid syntax, but no ; makes it kind of hard to read |
def some_method() body end |
# good |
def some_method |
body |
end |
---- |
One exception to the rule are empty-body methods. |
[source,ruby] |
---- |
# good |
def no_op; end |
---- |
=== Endless Methods |
Only use Ruby 3.0's endless method definitions with a single line |
body. Ideally, such method definitions should be both simple (a |
single expression) and free of side effects. |
NOTE: It's important to understand that this guideline doesn't |
contradict the previous one. We still caution against the use of |
single-line method definitions, but if such methods are to be used, |
prefer endless methods. |
[source,ruby] |
---- |
# bad |
def fib(x) = if x < 2 |
x |
else |
fib(x - 1) + fib(x - 2) |
end |
# good |
def the_answer = 42 |
def get_x = @x |
def square(x) = x * x |
# Not (so) good: has side effect |
def set_x(x) = (@x = x) |
def print_foo = puts("foo") |
---- |
=== Double Colons [[double-colons]] |
Use `::` only to reference constants (this includes classes and modules) and constructors (like `Array()` or `Nokogiri::HTML()`). |
Do not use `::` for regular method calls. |
[source,ruby] |
---- |
# bad |
SomeClass::some_method |
some_object::some_method |
# good |
SomeClass.some_method |
some_object.some_method |
SomeModule::SomeClass::SOME_CONST |
SomeModule::SomeClass() |
---- |
=== Colon Method Definition [[colon-method-definition]] |
Do not use `::` to define class methods. |
[source,ruby] |
---- |
# bad |
class Foo |
def self::some_method |
end |
end |
# good |
class Foo |
def self.some_method |
end |
end |
---- |
=== Method Definition Parentheses [[method-parens]] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.