Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 41 / 68

Enum Basics

In this lesson you will learn to reproduce an enum in Ruby with a module, so a fixed set of options can be handled safely. This is for anyone searching for "Ruby enum how to use".

Ruby has no dedicated enum syntax, but gathering constants inside a module reproduces one. Use it when you want to limit the possible values in advance, the way a traffic light only has red, green, and amber.

The sample code defines three constants - RED, GREEN, BLUE - inside a Color module as symbols (values such as :red). Notice how they are referenced with ::, as in Color::RED.

A common stumbling block for beginners is the difference between a symbol and a string. A symbol such as :red looks like a string but is handled differently internally, including in comparison performance. Ruby uses symbols heavily for fixed values like these.

A named constant conveys intent far better than a string or a number scattered through the code, and it also guards against typos.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)