text
stringlengths
0
444
----
=== Safe navigation
Avoid chaining of `&.`. Replace with `.` and an explicit check.
E.g. if users are guaranteed to have an address and addresses are guaranteed to have a zip code:
[source, ruby]
----
# bad
user&.address&.zip
#good
user && user.address.zip
----
If such a change introduces excessive conditional logic, consider other approaches, such as delegation:
[source, ruby]
----
#bad
user && user.address && user.address.zip
#good
class User
def zip
address&.zip
end
end
user&.zip
----
=== Spaces and Braces [[spaces-braces]]
No spaces after `(`, `[` or before `]`, `)`.
Use spaces around `{` and before `}`.
[source,ruby]
----
# bad
some( arg ).other
[ 1, 2, 3 ].each{|e| puts e}
# good
some(arg).other
[1, 2, 3].each { |e| puts e }
----
`{` and `}` deserve a bit of clarification, since they are used for block and hash literals, as well as string interpolation.
For hash literals two styles are considered acceptable.
The first variant is slightly more readable (and arguably more popular in the Ruby community in general).
The second variant has the advantage of adding visual difference between block and hash literals.
Whichever one you pick - apply it consistently.
[source,ruby]
----
# good - space after { and before }
{ one: 1, two: 2 }
# good - no space after { and before }
{one: 1, two: 2}
----
With interpolated expressions, there should be no padded-spacing inside the braces.
[source,ruby]
----
# bad
"From: #{ user.first_name }, #{ user.last_name }"
# good
"From: #{user.first_name}, #{user.last_name}"
----
=== No Space after Bang [[no-space-bang]]
No space after `!`.
[source,ruby]
----
# bad
! something
# good
!something
----
=== No Space inside Range Literals [[no-space-inside-range-literals]]
No space inside range literals.
[source,ruby]
----
# bad
1 .. 3
'a' ... 'z'
# good
1..3
'a'...'z'
----