Skip to content

alexherbo2/enum.rb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 

Repository files navigation

Enum for Ruby

A Ruby implementation of enumerated type for educational purposes.

Heavily based on Crystal.

Overview

An enum is a set of integer values, where each value has an associated name.

For example:

require 'enum'

class Color < Enum
  member :Red # 0
  member :Green # 1
  member :Blue # 2
end

Values start with the value 0 and are incremented by one, but can be overwritten.

To get the underlying value you invoke value on it:

Color::Green.value # ⇒ 1

Enums from integers

An enum can be created from an integer:

Color.new(1).to_s # ⇒ "Green"

Values that don’t correspond to enum’s constants are allowed: the value will still be of type Color, but when printed you will get the underlying value:

Color.new(10).to_s # ⇒ "10"

This method is mainly intended to convert integers from C to enums in Ruby.

Question methods

Color::Red.red? # ⇒ true
Color::Blue.red? # ⇒ false

Usage

def paint(color)
  case color
  when Color::Red
    # ...
  else
    # Unusual, but still can happen.
    raise "Unknown color: #{color}"
  end
end

Reference

Releases

No releases published

Packages

No packages published

Languages