What does :: do?

前端 未结 5 1694
南旧
南旧 2020-12-16 23:18

I have some inherited code that I am modifying. However, I am seeing something strange(to me).

I see some code like this:

::User.find_by_email(params         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 23:51

    Ruby uses (among other things) lexical scoping to find constant names. For example, if you have this code:

    module Foo
      class Bar
      end
    
      def self.get_bar
        Bar.new
      end
    end
    
    class Bar
    end
    

    The Foo.get_bar returns an instance of Foo::Bar. But if we put :: in front of a constant name, it forces Ruby to only look in the top level for the constant. So ::Bar always refers the top-level Bar class.

    You will run into situations in Ruby where the way your code is being run will force you to use these 'absolute' constant references to get to the class you want.

提交回复
热议问题