Syntax rules in a Ruby style guide exist for one reason: so that a reviewer spends attention on behaviour, not layout. The conventions below are the ones most Ruby teams converge on, and each comes with a short reason so you can decide which to adopt.
Indentation and line length
Use two spaces, never tabs. Keep lines short enough to read side by side in a diff, around 100 characters is a common ceiling. When a method chain gets long, break it with a leading dot so each step sits on its own line.
active_emails = users
.select(&:active?)
.map(&:email)
.uniq
Parentheses
Use parentheses around method arguments when the method is called for its return value. Leave them off for DSL style calls such as puts, require, attr_reader or RSpec matchers, where the bare form is idiomatic.
total = calculate_total(items, tax_rate)
attr_reader :name, :email
puts "Done"
Blocks
Prefer braces for single line blocks that return a value and do...end for multi line blocks or blocks run for side effects.
names = people.map { |person| person.name.upcase }
people.each do |person|
Mailer.welcome(person).deliver_later
person.touch(:welcomed_at)
end
Conditionals
- Use a modifier
iforunlessfor a short single statement:return if items.empty?. - Never use
unlesswithelse. Flip the condition and useif. - Avoid nested ternaries. One ternary on a line is fine; two is a method waiting to be extracted.
- Prefer guard clauses over deep nesting, so the main path of a method stays at the left margin.
def discount_for(order)
return 0 unless order.customer
return 0 if order.total < 50
order.customer.loyal? ? 10 : 5
end
Spacing
Put spaces around operators, after commas and inside braces for hashes and blocks, but not inside parentheses or square brackets. Separate method definitions with one blank line, and use blank lines inside a method to split it into logical steps.
Enforce it with a tool
Agreeing on syntax is only half of the job. A linter such as RuboCop, run in CI and in the editor, turns the guide into something automatic and keeps style discussion out of code review entirely.