Skip to content

Instantly share code, notes, and snippets.

@eliotsykes
Last active September 28, 2023 08:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eliotsykes/e64786ef97479ba234b3583febb025b2 to your computer and use it in GitHub Desktop.
Save eliotsykes/e64786ef97479ba234b3583febb025b2 to your computer and use it in GitHub Desktop.
Multiline expressions in Ruby

How to break long lines up in Ruby

This page lists the options for breaking single-line expressions into multiple lines in Ruby.

Developers and teams need to come to their own decisions about which guideline(s) they prefer (preferences below are just my personal choices and I encourage you to disregard them).

# With trailing parens
x = [1, 2, 3].join(
  '-'
)

# With leading dot
x = [1, 2, 3]
  .join '-'

# With trailing `=`
x =
  [1, 2, 3].join '-'

# I'm not a big fan of the following options but its
# absolutely OK if you are, choose what you find
# works best for your situation.

# With trailing dot
x = [1, 2, 3].
  join '-'

# With slash
x = [1, 2, 3].join \
  '-'

# With leading `=`, requires slash
x \
  = [1, 2, 3].join '-'

# With leading parens, requires slash
x = [1, 2, 3].join \
  ('-')

Related reading

@DarylCantrell
Copy link

The last two are not really valid examples. It's not the leading '=' or '(' that continues the line. It's the backslash on the preceding line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment