0
0
Rubyprogramming~10 mins

Constants in classes in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Constants in classes
Define Class
Set Constant inside Class
Access Constant via Class
Use Constant Value
End
This flow shows how a constant is set inside a class and then accessed using the class name.
Execution Sample
Ruby
class MyClass
  MY_CONST = 10
end

puts MyClass::MY_CONST
Defines a class with a constant and prints the constant value using class scope resolution.
Execution Table
StepActionCode LineState ChangeOutput
1Define class MyClassclass MyClassClass MyClass created
2Set constant MY_CONST to 10MY_CONST = 10MY_CONST set to 10 inside MyClass
3End class definitionendClass MyClass finalized
4Access constant MY_CONST via MyClassputs MyClass::MY_CONSTRetrieve MY_CONST value 1010
💡 Program ends after printing the constant value 10.
Variable Tracker
VariableStartAfter Step 2Final
MyClass::MY_CONSTundefined1010
Key Moments - 2 Insights
Why do we use :: to access the constant?
The :: operator accesses constants or methods inside a class or module. Here, it tells Ruby to look inside MyClass for MY_CONST, as shown in execution_table step 4.
Can we change the value of MY_CONST after setting it?
Constants in Ruby can technically be changed but Ruby warns you. In this example, MY_CONST is set once and used as 10, as shown in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of MY_CONST after step 2?
Anil
B10
Cundefined
Derror
💡 Hint
Check the 'State Change' column in row for step 2 in execution_table.
At which step is the constant MY_CONST accessed to print its value?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Look for the 'Action' column mentioning 'Access constant' in execution_table.
If we tried to access MY_CONST without MyClass:: prefix, what would happen?
AIt would cause an error
BIt would print 10
CIt would print nil
DIt would print 0
💡 Hint
Constants inside classes need the class name prefix to be accessed, as shown in execution_table step 4.
Concept Snapshot
class MyClass
  MY_CONST = 10  # Define constant inside class
end

Access with MyClass::MY_CONST
Constants are fixed values inside classes
Use :: to access constants inside class scope
Full Transcript
This example shows how to define a constant inside a Ruby class and access it. First, the class MyClass is created. Then, inside it, the constant MY_CONST is set to 10. After the class ends, we access the constant using MyClass::MY_CONST and print its value. Constants inside classes are accessed with the :: operator to specify the class scope. Changing constants is possible but not recommended. The program prints 10 as the output.