What's the best way to do multiple requires in Ruby?

The plain way is the best way.

You could do this, but it trades clarity for cleverness--a poor bargain:

[
  'rubygems',
  'rack',
  'rails'
].each(&method(:require))

Skip the "rescue" with the fancy error message. Everyone knows what it means when a require throws a stack trace.

If you want to make it easier for someone using your program to have the required gems installed, check out bundler.


All of the ruby scripts i have seen just list one require per line like you have first.

require 'rubygems'
require 'rack'
require 'rails'

In the first one it is clear what you're doing.

In the second it requires someone to decode what you're doing.

It seems a bit whimsical to force everybody to decode what you're doing so you can save a few lines of typing (and that only if you're using a whole lot of libraries in one source file which is a bit of code smell in and of itself). Remember that code is read an order of magnitude or three times as often as it is written. If it's a choice between easy writing or easy reading, the reading should win out.

Tags:

Ruby

Rubygems