skrat
skrat

Reputation: 5562

'Object' named class in Ruby

Does it have any drawbacks if I use Object as a name for my class inside module?

module Some
  class Object; end
end

Upvotes: 3

Views: 204

Answers (3)

August Lilleaas
August Lilleaas

Reputation: 54593

There are some pitfalls, but it works. If you do this, you'll expand the Object class that is already in Ruby.

class Object
  def hello
  end
end

When you namespace it you'll create a new class, though, in that namespace.

module Foo
  class Object
    # ...
  end
end

Technically speaking, this is not a problem.

One downside is that you have to use ::Object when you want to refer to the built-in Object class. You don't doo that very often, though, so it's not a big problem.

The other problem is that can be very confusing for other developers, which you should take into consideration. It's hard to tell from your snippet what this Some::Object class of yours does, but perhaps Some::Record, Some::Entity makes more sense.

Upvotes: 3

Greg Campbell
Greg Campbell

Reputation: 15302

Actually, this code ought to work with no problems, since it's in a module and thus namespaced. For a simple test:

module Some
  class Object
    def foo
      "bar"
    end
  end
end

Some::Object.new.foo # "bar"
Some::Object.new.class # "Some::Object"

# And it doesn't pollute the global namespaced Object class:
Object.new.respond_to?(:foo) # false

It could potentially be confusing or ambiguous, however, if you include Some in another class or module, inside which Object will refer to Some::Object. It still won't affect anything outside that class or module, though.

Upvotes: 10

Marc W
Marc W

Reputation: 19241

Object is a reserved word in Ruby, so you should not use it as a name for your class.

Upvotes: -2

Related Questions