7

Is there any difference between doing

class Bus::Driver
end

and

module Bus
  class Driver
  end
end

If not, which syntax is preferred?

0

4 Answers 4

7

Is there any difference between doing [...]?

The only difference is that in class Bus::Driver the Bus module must be already defined, while the same does not stand for the second.

Which syntax is preferred?

This is not a constructive question but I personally prefer the second because it states explicitly that Bus is a module, while with the first I cannot see at first glance if Bus is a module or a class.

Sign up to request clarification or add additional context in comments.

Comments

3

This, on its own:

class Bus::Driver
end

will result in an error NameError: uninitialized constant Bus

So at some point you have to declare class Bus or module Bus. It doesn't have to be the full hierarchy each time though.

I tend to have an early require that sets up the namespaces, then use the more condensed form in the rest of my files. I'm not aware that there is any preferred approach - definitely nothing that you would be criticised for.

Comments

1

First syntax is preferred when you have various classes of a module spread across multiple files in a project; and provided module is always defined in PATH. Such as, while making a gem.

Second is more central, and should be done when details are concerned. module doesn't not only include class, it includes methods and constants etc for namespace too; which are useful.

Comments

0

There is an additional difference between those declarations when inheritance is involved:

Let's assume Driver inherits from a Person class.

class Bus::Driver < Person
end
module Bus
  class Driver < Person
  end
end

When Ruby tries to resolve the Person constant, in the first declaration it only looks for ::Person. The second one looks for both Bus::Person and ::Person.

Depending on your circumstances this could make one declaration preferrable to the other.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.