Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant in class << self block

Tags:

ruby

In the following fragment, is it possible to refer to the FOO constant from outside the module, and if so, how?

module X
  class << self
    FOO = 2
  end
end
like image 571
Michiel de Mare Avatar asked Feb 17 '10 13:02

Michiel de Mare


People also ask

What do you mean by constants in Ruby?

A constant in Ruby is like a variable, except that its value is supposed to remain constant for the duration of a program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant.

What is self in a class method Ruby?

self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.

What is the use of self in Ruby?

self is a reserved keyword in Ruby that always refers to the current object and classes are also objects, but the object self refers to frequently changes based on the situation or context. So if you're in an instance, self refers to the instance. If you're in a class, self refers to that class.


1 Answers

class <<X
  self
end::FOO

or

class Object
  def metaclass
    class <<self
      self
    end
  end
end

X.metaclass::FOO
like image 69
sepp2k Avatar answered Oct 03 '22 19:10

sepp2k