dan dan - 2 months ago 5
Ruby Question

Recommended indentation style for Ruby `if` blocks that assign a value to a variable?

Which of these is better Ruby code formatting style, and why?

Option A:

def load_business
@business ||= if params[:badge_uuid]
# some code
else
# some other code
end
end


Option B:

def load_business
@business ||= if params[:badge_uuid]
# some code
else
# some other code
end
end

Answer

It's a subjective question, so we can only give (hopefully reasoned) opinions. I always use option A. My rationale:

  1. The block of code is opened and closed at the same indentation-level, that creates a "visual cohesion".

  2. If the variable name changes its size, you don't need to edit anything (some text editors handle this automatically, though).

  3. You create a "hole" in the source code. The larger the variable name, the bigger the hole. IMO this is visually annoying. Also, you have less space available till reaching some reasonable 80/100-char limit.

I use this style when writing multi-line hashes/arrays/... (note the comma also in the last element so we can re-order them easily and in diff-friendly way):

hash = {
  :a => 1,
  :b => 2,
}

array = [
  :a, 
  :b,
]
Comments