Victor L
Victor L

Reputation: 10230

What's the difference between "module self::X" and "module X"?

How is

module self::GenName

different from simply

module GenName

Note that this module is nested inside another module.

Upvotes: 0

Views: 61

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Since

module M1
  puts "self = #{self}"
  module self::GenName
    puts Module.nesting
    def self.gen_name
    end
  end
end
  # self = M1
  # M1::GenName
  # M1

we see that M1 is the same as

module M1
  module M1::GenName
    puts Module.nesting
    def self.gen_name
    end
  end
end
  # M1::GenName
  # M1

which should come as no surprise. GenName is referenced (for example)

M1::GenName.methods(false)
  #=> [:gen_name]

in both cases. If we instead write

module M2
  module GenName
    puts Module.nesting
    def self.gen_name
    end
  end
end
  # M2::GenName
  # M2

then

M2::GenName.methods(false)
  #=> [:gen_name]

This shows that Ruby references GenName the same way in both cases. I'm convinced there's no difference if self. is added, but I also think the above falls short of a proof.

Upvotes: 1

Related Questions