Teik Jun
Teik Jun

Reputation: 391

Should I split a ruby single-line if statement into multi-line if statement because the line is long?

I have a ruby single-line statement that is very long, about 200 characters. According to a ruby style guide, single-line if statement is favored here because the body is single-line.

address = Module::InnerModule::Class.new(long_address) if Module::Class.new(long_address).is_good? 

But, 200 characters is way over the usual threshold for line length (which is usually 120 at most). Should I split the if statement into a multi-line statement in order to reduce the line length (or should I just accept that the line is long)?

if Module::Class.new(long_address).is_good? 
  address = Module::InnerModule::Class.new(long_address)

Also, what happens if the line is still very long after splitting? What is the best practice here? I'm new to Ruby, so I would appreciate any advice on the best practice here.

Upvotes: 1

Views: 308

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84353

Style questions aside, if you want to maintain your current semantics, you can break lines at certain keywords and operators without escaping newlines with backslashes. For example:

address =
  Module::InnerModule::Class.new(long_address) if
    Module::Class.new(long_address).is_good?

Otherwise, change your semantics or refactor your code to fit your desired line length and chosen style. Questions about how to split lines are answerable, but the “best” way to split, indent, or refactor are largely subjective, and mostly amount to a combination of readability and intent.

Upvotes: 1

Related Questions