Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Enums in Ruby
3.
Importance of Enums in Ruby
4.
How to Use Enums in Ruby
4.1.
Using Constants
4.1.1.
Implementation
4.1.2.
Explanation
4.2.
Using Symbols
4.2.1.
Implementation
4.2.2.
Explanation
4.3.
Using a Class with Class Constants
4.3.1.
Implementation
4.3.2.
Explanation
4.4.
Using Hash
4.4.1.
Implementation
4.4.2.
Explanation
4.5.
Using Arrays
4.5.1.
Implementation
4.5.2.
Explanation
5.
Default Enum Methods in Ruby
5.1.
Question Marks ('status?')
5.1.1.
Example
5.2.
Bang Methods ('status!')
5.2.1.
Example
5.3.
Scopes
5.3.1.
Example
6.
Toolkit for Using Enums in Ruby
7.
Frequently Asked Questions
7.1.
What are Enums?
7.2.
Why does Ruby not support built-in enums?
7.3.
What are the different ways to create enums in Ruby?
7.4.
How to Use Enums in Ruby with default methods?
8.
Conclusion 
Last Updated: Mar 27, 2024
Easy

How to Use Enums in Ruby?

Introduction

In the world of programming, Ruby is one of the most powerful programming languages that help developers handle and organise data efficiently. Enums in Ruby are a useful feature in writing maintainable code.

How to Use Enums in Ruby?

In this article, we will learn How to Use Enums in Ruby in detail, along with some examples.

Also, read enumerators in Ruby.

Enums in Ruby

Enums, or Enumerations, is a fundamental data type that allows programmers to define a set of named constants. It allows developers to assign meaningful names to specific values, thus making our code more readable and understandable. It even reduces the errors. 

Ruby on Rails

While Ruby does not have built-in support for enums like other programming languages, we can create enums using other methods to have similar functionality.

Check out this article on Enumerable objects in Ruby.

Importance of Enums in Ruby

Enums in Ruby are very important in several ways, including:

  • Enums allow users to use meaningful names for constants, thus improving the readability of the code.
     
  • Using enums in our programs can reduce the use of random numbers. This, in turn, decreases the risk of errors.
     
  • With the help of enums, any change or update in the code can be done in one place, thus offering simplified code maintenance.
     
  • Named constants give clearer debug messages, thus allowing developers to identify the issues easily.
     

Next, let us understand How to Use Enums in Ruby with the help of a few examples.

How to Use Enums in Ruby

We can use different ways to create enums in Ruby. Some of the common methods are:

Using Constants

Enums can be created in Ruby using constants by defining a module with named constants to represent a set of different values. Here the module serves as the enum.

Implementation

#Defining module
module Colors
  RED = 1
  GREEN = 2
  BLUE = 3
end

# Using the Enum
color = Colors::GREEN
You can also try this code with Online Ruby Compiler
Run Code

Explanation

In the example above, we have defined a module 'Colors' with constants' RED,' 'GREEN,' and 'BLUE .' Each constant is assigned a value representing a color. Next, we used the 'GREEN' constant from the 'Colors' module and assigned it to the variable 'color.' The variable 'color' holds the value '2' representing green color.

Using Symbols

In this method, we use meaningful names to represent different values. For example, if we want to create an enum-like structure for colors in Ruby, instead of representing colors with integers, we can provide names to them using symbols. These symbols, once assigned, cannot be changed. Symbols are represented using a colon followed by a name (e.g., ':symbol_name').

Implementation

module Colors
  RED = :red
  GREEN = :green
  BLUE = :blue
end

# to access enum values
color = Colors::GREEN

# Performing comparisons on enum values
if color == Colors::RED
  puts "The color is red."
elsif color == Colors::GREEN
  puts "The color is green."
elsif color == Colors::BLUE
  puts "The color is blue."
else
  puts "Unknown color."
end
You can also try this code with Online Ruby Compiler
Run Code

 

Output

The color is green.
You can also try this code with Online Ruby Compiler
Run Code

Explanation

In the example above, we have defined a module 'Colors' with constants 'RED,' 'GREEN,' and 'BLUE.' Each constant is assigned a symbol representing a color. Using symbols brings clarity to our code.

Using a Class with Class Constants

We can create enum-like behaviour using a Ruby class with class constants. These class constants are defined within the class and remain accessible throughout the scope of a class.

Implementation

class Colors
  RED = 1
  GREEN = 2
  BLUE = 3
end

# Using the enum
color = Colors::RED
You can also try this code with Online Ruby Compiler
Run Code

Explanation

In the example above, we have defined a class 'Colors' with class constants' RED,' 'GREEN,' and 'BLUE .' Each constant is assigned a value representing a color. Next, we used the 'RED' constant from the 'Colors' class and assigned it to the variable' color .' The variable 'color' holds the value '1' representing green color.

Using Hash

With the help of hash, the programmer can set custom values for each enum option. Creating enums using hashes is helpful when you need non-integer values or perform complex mappings.

Implementation

COLORS = {
  RED: '#FF0000',
  GREEN: '#00FF00',
  BLUE: '#0000FF'
}

# Using the enum
selected_color = COLORS[:GREEN]
You can also try this code with Online Ruby Compiler
Run Code

Explanation

In the example above, the 'COLORS' hash represents our enum. The hash keys 'RED,' 'GREEN,' and 'BLUE' represent the constant names and the values' #FF0000', '#00FF00', and '#0000FF', respectively.

Using Arrays

Enums can be created using arrays when you need continuous integer values starting from 0.

Implementation

# Defining the enum using an array
colors = [
  :red,
  :blue,
  :green
].freeze

# Accessing enum values
puts colors[0]  # Output: :red
puts colors[1]  # Output: :blue
puts colors[2]  # Output: :green
You can also try this code with Online Ruby Compiler
Run Code

 

Output

red
blue
green
You can also try this code with Online Ruby Compiler
Run Code

Explanation

In the above example, we have created a simple enum for colors using an array, where each color is represented by its index in the array.

Default Enum Methods in Ruby

When you define an enum in your model in Ruby on Rails, some default methods are also generated for each enum variable. These methods simplify checks, updates, and filtering based on the enum values.

Default enum methods in Ruby on rails

 

Let us see How to Use Enums in Ruby with these default methods.

To understand the default methods better, let us take an example of a model called 'Task' with an enum column 'status' that states the task status with values 'pending,' 'in_progress,' and 'completed'.

class Task < ApplicationRecord
  enum status: [:pending, :in_progress, :completed]
end
You can also try this code with Online Ruby Compiler
Run Code

Question Marks ('status?')

These methods return a boolean value (True/False) indicating whether the enum's current value matches the specified enum value.

Example

task = Task.new(status: :in_progress)
task.status_pending? # Output: false
task.status_in_progress? # Output: true
You can also try this code with Online Ruby Compiler
Run Code

Bang Methods ('status!')

Bang methods allow programmers to update the value of an enum column to a specific enum value.

Example

task = Task.new(status: :in_progress)
task.status_completed! # Changing the 'status' value to 'completed'
task.status # Output: "completed"
You can also try this code with Online Ruby Compiler
Run Code

Scopes

Enumerated values are automatically assigned scopes that allow programmers to filter records based on their enum values.

Example

# To fetch all tasks with 'in_progress' status
in_progress_tasks = Task.in_progress
# To fetch all completed tasks
completed_tasks = Task.completed
You can also try this code with Online Ruby Compiler
Run Code

Toolkit for Using Enums in Ruby

You can have a sniff at some of the tips and suggestions on How to Use Enums in Ruby.

  • It is advisable to use meaningful names for enum constants to make your code self-explanatory.
     
  • Enumerate commonly used values instead of using magic numbers.
     
  • Using hashes rather than arrays to define enums is a good practice.
     
  • It is recommended not to use consecutive integers like 0, 1, 2, 3,… Instead, you can use 0, 5, 10, 15,... This allows you to add new values in the future.
     
  • You should group related constants within separate enums to organize your code.
     
  • Use loops to go through all the enum values one by one to perform tasks on all the constants concisely.
     
  • It is advised to use the freeze method to make the enum values immutable if you do not want to modify them later.

Frequently Asked Questions

What are Enums?

Enums, also known as Enumerations, is a fundamental data type that allows programmers to define a set of named constants. It allows developers to assign meaningful names to specific values, thus making our code more readable and understandable. 

Why does Ruby not support built-in enums?

Ruby does not support built-in enums because the programming language focuses more on simplicity and flexibility. Instead, Ruby offers many ways, like using constants or hashes to have a similar feature. 

What are the different ways to create enums in Ruby?

Ruby does not have built-in support for enums like other programming languages. We can create enums using other methods like using constants with the help of symbols, using a class with class constants, and using a hash.

How to Use Enums in Ruby with default methods?

Enums in Ruby provide three default methods, Question Marks ('status?'), Bang Methods ('status!') and scopes. These methods simplify checks, updates, and filtering based on the enum values. 

Conclusion 

Kudos on finishing this article! We have discussed the importance and How to Use Enums in Ruby in detail. We have used different ways to create enums in Ruby.

We hope this blog has helped you enhance your knowledge of How to Use Enums in Ruby.

Keep learning! We suggest you read some of our other articles related to Ruby: 

  1. Introduction to Ruby
  2. Ruby on Rails
  3. Ruby on rails interview questions
     

Refer to our Guided Path to enhance your skills in DSA, Competitive Programming, JavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas!

But suppose you are just a beginner and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problems, interview experiences, and interview bundles.

Best of Luck! 

Happy Learning!

Live masterclass