Matt Briggs
Matt Briggs

Reputation: 42158

Can somebody please explain ruby constant lookup for me?

More specifically:

EDIT: I am talking about stuff like this

module Foo
  THING = 'thing'
  module Bar
    puts THING
  end
end
#=> thing

module Foo::Bar
  puts THING
end
#=> NameError: uninitialized constant Foo::Bar::THING

Upvotes: 4

Views: 649

Answers (2)

Ian
Ian

Reputation: 2108

When do you need to prefix the scope with :: (like ::Foo::Bar)

When there's another constant with the same name in the current namespace.

When is directly referring to a scoped const ok? (just Foo::Bar)

When there isn't another constant with the same name in the current namespace. Ie. when that identifier is unambiguous. Similarly, you could just use Bar to aid readability if it was unambiguous.

Is there a good reason why this behavior is so confusing?

It's balancing readability and ease of use against specificity. You don't always want to have to do ::Foo::Bar::Baz::Boo (the globally unique identifier) when you're deep down in your namespace.

Upvotes: 5

Denis de Bernardy
Denis de Bernardy

Reputation: 78413

In as far as I've understood/experienced it: when in a module/class Foo, then Bar refers to Foo::Bar unless it doesn't exist -- in which case it means ::Bar.)

Please take it with a grain of salt, though, because I'm new to ruby as well. :-P

Upvotes: 0

Related Questions