How to create an enumeration of constants with and without explicit values in Ruby

1 Answer

0 votes
# 
# Title: Enumeration of Constants in Ruby
# Example with and without explicit values
#

# Ruby does not have native enums like some languages,
# but we can simulate them using modules, constants, or classes.

# ---------------------------------------------------------
# Enum WITHOUT explicit values (auto‑increment simulation)
# ---------------------------------------------------------
module Color
  RED   = 0
  GREEN = 1
  BLUE  = 2
end

# ---------------------------------------------------------
# Enum WITH explicit values
# ---------------------------------------------------------
module Status
  OK       = 1
  WARNING  = 5
  ERROR    = 6
  CRITICAL = 10
end

# ---------------------------------------------------------
# Demonstration
# ---------------------------------------------------------
puts "Enum without explicit values:"
puts "RED = #{Color::RED}"
puts "GREEN = #{Color::GREEN}"
puts "BLUE = #{Color::BLUE}"

puts "\nEnum with explicit values:"
puts "OK = #{Status::OK}"
puts "WARNING = #{Status::WARNING}"
puts "ERROR = #{Status::ERROR}"
puts "CRITICAL = #{Status::CRITICAL}"

# Ruby also allows freezing modules to prevent modification
module FrozenDays
  SUNDAY = 0
  MONDAY = 1
  TUESDAY = 2
  freeze
end

puts "\nImmutable enum example:"
puts "SUNDAY = #{FrozenDays::SUNDAY}"

# Attempt to modify (will raise an error if uncommented)
# FrozenDays::SUNDAY = 99

puts "After modification attempt, SUNDAY = #{FrozenDays::SUNDAY}"

# ---------------------------------------------------------

=begin
run:

Enum without explicit values:
RED = 0
GREEN = 1
BLUE = 2

Enum with explicit values:
OK = 1
WARNING = 5
ERROR = 6
CRITICAL = 10

Immutable enum example:
SUNDAY = 0
After modification attempt, SUNDAY = 0

=end

 



answered 3 hours ago by avibootz

Related questions

...