Skip to content

Example: Class Constant

Andrias Meisyal edited this page Jul 16, 2017 · 2 revisions

A class constant is a variable that can only be assigned once and its value can not be modified once assigned. As mentioned on Class Attribute Rules, a constant is generated if an attribute is set to readonly and static. For instance, this Circle class below contains an attribute PI.

Class Constant

If you generate Circle class above, this extension will generate:

circle.rb

class Circle
  PI = 3.14159

  def initialize()
  end

  def to_s
    "Your string representation of the object will be written here."
  end
end

PI constant defined as a public attribute. You may change it to be a private because Ruby can handle it. The generated code for this case will look like:

circle.rb

class Circle
  PI = 3.14159
  private_constant :PI

  def initialize()
  end

  def to_s
    "Your string representation of the object will be written here."
  end
end

Note that the example above uses default configuration of the extension.

Clone this wiki locally