wmock
wmock

Reputation: 5492

Ruby Constants and Namespacing

Is there a difference between the following 2 snippets of code?

# 1st snippet
class A
  class B
    # some code here
  end
end

# 2nd snippet
class A::B
  # some code here
end

If there is a difference, can you help me understand what the difference is and why you would use one version versus the other?

Upvotes: 2

Views: 337

Answers (1)

Scott S
Scott S

Reputation: 2746

This seems to be mostly syntactic sugar for organizing your code - whichever way makes sense to you is the "correct" way. The only exception is that with the 2nd snippet, if class A hasn't already been defined you'll get an error. For the most part this question is a duplicate of this one, though since you are nesting classes in classes instead of classes in a module, I'll go ahead and link the Module docs, which explains the difference between modules and classes in Ruby and may help you interpret that SO answer in the context of your own question.

Upvotes: 1

Related Questions