Enums in Ruby



What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.


Posted 2008-09-16T19:02:09.073

Reputation: 6 511

6@auramo, good question, and great choice for the best answer. Love it or hate it, you get no type-safety and (at least in Ruby) no typo-safety. I was thrilled when I discovered enums in C# and later in Java (pick a value, but from these!), Ruby doesn't provide a real way to do that in any case at all. – Dan Rosenstark – 2010-03-11T09:57:38.903

2The problem with this question is that Java and C# enums are dramatically different things. A Java enum member is an object instance and a singleton. A Java enum can have a constructor. In contrast, C# enums are based off Primitive values. Which behaviour is the questioner looking for? While it's likely the case that the C# case is wanted, Java is explicitly mentioned, rather than C or C++, so there is some doubt. As for suggesting that there's no way to be 'safe' in Ruby, that's transparently false, but you have to implement something more sophisticated. – user1164178 – 2015-02-14T06:33:09.007



Two ways. Symbols (:foo notation) or constants (FOO notation).

Symbols are appropriate when you want to enhance readability without littering code with literal strings.

postal_code[:minnesota] = "MN"
postal_code[:new_york] = "NY"

Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that.

module Foo
  BAR = 1
  BAZ = 2
  BIZ = 4

flags = Foo::BAR | Foo::BAZ # flags = 3


Posted 2008-09-16T19:02:09.073

Reputation: 4 617

what about order? – dfrankow – 2012-02-17T15:04:48.797

@dfrankow, what do you mean? I've never heard of order as a concern in the context of C# enums. – mlibby – 2012-02-21T14:09:11.400

Don't know about C#, but Java enums have order, and it is used: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html. "Note that each enum type has a static values method that returns an array containing all of the values of the enum type in the order they are declared. This method is commonly used in combination with the for-each loop to iterate over the values of an enumerated type."

– dfrankow – 2012-02-21T14:11:32.373

@drankow, ah. For that to be automatic you would need to look at something like http://www.rubyfleebie.com/enumerations-and-ruby/ or http://code.dblock.org/how-to-define-enums-in-ruby which support this behavior. Otherwise, if you use the constants approach, you can define a method like Foo.values that returns the constants as an array.

– mlibby – 2012-02-21T14:21:23.953

7Wouldn't a module be better to group constants - as you're not going to be making any instances of it? – thomthom – 2012-03-14T13:37:19.840

@thomthom absolutely, yes. I've changed the answer. If there is no close coupling of the enums to the context of a class where it would make sense to declare them, then a module makes more sense. – mlibby – 2012-03-23T12:51:20.173

As well, the module would be faster, as the other one has a hash lookup. Small hash, sure, but still. – baash05 – 2012-07-06T00:04:36.700

2Just a comment. Ruby's a bit of a pain about naming conventions but not really obvious about them until you trip over them. The names of the enums must be all caps and the first letter of the module name must be capitalized for ruby to know that the module is a module of constants. – Rokujolady – 2013-04-08T18:41:30.397

2What if these enum is too be stored to the database? Will symbol notation works? I doubt... – Phương Nguyễn – 2010-06-11T03:44:41.733

I would use the constants approach if I were saving to a database. Of course then you have to do some sort of lookup when pulling the data back out of the DB. You could also use something like :minnesota.to_s when saving to a database to save the string version of the symbol. Rails, I believe, has some helper methods to deal with some of this. – mlibby – 2010-06-11T12:40:52.227

2Not entirely true. The first letter of the constant must be capitalized, but not all letters need to be. This is a matter of convention preference. For example, all module names and class names are actually constants too. – Michael Brown – 2014-03-10T23:02:19.643

2i like the 2nd idea very much. thank you! – Martin Labuschin – 2010-08-20T12:22:31.540

What if I want to do a type check as these are just constants? – Gayan Weerakutti – 2018-04-20T13:20:52.180


I'm surprised that no one has offered something like the following (harvested from the RAPI gem):

class Enum


  def self.enum_attr(name, num)
    name = name.to_s

    define_method(name + '?') do
      @attrs & num != 0

    define_method(name + '=') do |set|
      if set
        @attrs |= num
        @attrs &= ~num


  def initialize(attrs = 0)
    @attrs = attrs

  def to_i

Which can be used like so:

class FileAttributes < Enum
  enum_attr :readonly,       0x0001
  enum_attr :hidden,         0x0002
  enum_attr :system,         0x0004
  enum_attr :directory,      0x0010
  enum_attr :archive,        0x0020
  enum_attr :in_rom,         0x0040
  enum_attr :normal,         0x0080
  enum_attr :temporary,      0x0100
  enum_attr :sparse,         0x0200
  enum_attr :reparse_point,  0x0400
  enum_attr :compressed,     0x0800
  enum_attr :rom_module,     0x2000


>> example = FileAttributes.new(3)
=> #<FileAttributes:0x629d90 @attrs=3>
>> example.readonly?
=> true
>> example.hidden?
=> true
>> example.system?
=> false
>> example.system = true
=> true
>> example.system?
=> true
>> example.to_i
=> 7

This plays well in database scenarios, or when dealing with C style constants/enums (as is the case when using FFI, which RAPI makes extensive use of).

Also, you don't have to worry about typos causing silent failures, as you would with using a hash-type solution.


Posted 2008-09-16T19:02:09.073

Reputation: 4 131

1That's a great way to solve that particular problem, but the reason no one suggested it probably has to do with the fact that it's not much like C#/Java enums. – mlibby – 2012-02-17T14:21:35.620

1This is a bit incomplete, but serves as nice hint as to how you might implement solutions with a dynamic approach. It bears some resemblance to a C# enum with the FlagsAttribute set, but like the symbol/constant based solutions above, it's one answer of many. The problem is the original question, which is muddled in its intent (C# and Java aren't interchangeable). There are many ways to itemize objects in Ruby; selecting the right one depends on the problem being solved. Slavishly replicating features you don't need is misguided. The correct answer has to depend on the context. – user1164178 – 2015-02-14T06:46:23.447

1Of course, operators such as |, &amp; can be added too. – Charles – 2011-05-30T23:19:35.093


The most idiomatic way to do this is to use symbols. For example, instead of:

enum {


...you can just use symbols:

# You don't actually need to declare these, of course--this is
# just to show you what symbols look like.


This is a bit more open-ended than enums, but it fits well with the Ruby spirit.

Symbols also perform very well. Comparing two symbols for equality, for example, is much faster than comparing two strings.


Posted 2008-09-16T19:02:09.073

Reputation: 48 167

91So the Ruby spirit is: "Typos will compile" – mxcl – 2009-08-03T14:02:43.390

79Popular Ruby frameworks rely heavily on runtime metaprogramming, and performing too much load-time checking would take away most of Ruby's expressive power. To avoid problems, most Ruby programmers practice test-driven design, which will find not just typos but also logic errors. – emk – 2009-08-20T20:14:16.720

@MaxHowell Actually there is no compilation, it just would be evaluated and there is nothing wrong with that. – Jahan Zinedine – 2012-10-17T09:04:59.317

2Well, since ruby doesn't compile, I think the ruby way is "Convention over Configuration" which means "We hardcode stuff and you guess what what we hardcoded." – Rokujolady – 2013-04-08T18:43:37.127

1@emk, thanks for your comment, it really sums up the dynamic-lang crowd's thought on the thing. While I do think it's wrong, that's how it works :) – Dan Rosenstark – 2010-03-05T14:09:19.467

10@yar: Well, language design is a series of tradeoffs, and language features interact. If you want a good, highly-dynamic language, go with Ruby, write your unit tests first, and go with the spirit of the language. :-) If that's not what you're looking for, there are dozens of other excellent languages out there, each of which makes different tradeoffs. – emk – 2010-03-10T17:51:32.830

9@emk, I agree, but my personal issue is that I feel quite comfortable in Ruby, but I do not feel comfortable refactoring in Ruby. And now that I've started writing unit tests (finally), I realize that they are not a panacea: my guess is 1) that Ruby code doesn't get massively refactored that often, in practice and 2) Ruby is not the end-of-the-line in terms of dynamic languages, precisely because it's hard to refactor automatically. See my question 2317579 which got taken over, strangely, by the Smalltalk folks. – Dan Rosenstark – 2010-03-10T23:52:05.290

2@Max, the way Ruby works, what appears to be a typo at compile time may not be a typo at run time. Using symbols in Ruby is merely an idiomatic and performant way to do this. In a language like C, enums are really the only way to solve this problem. But in C# I see lots of people using strings to solve the "named index" problem rather than taking the time to build an enum. Strings have the same "typos will compile" problems as Ruby's symbols and confounds the IDE's autocomplete functionality. – mlibby – 2010-03-28T11:20:30.073

4Yeah, but using those strings would not be in the spirit of the C# language, it is simply a bad practice. – Ed S. – 2010-04-04T00:11:13.437

2@yar: For Ruby (and similar languages) to be truly usable and refactorable, you really do need excellent test coverage. The easiest way to do this is to never add a feature except to fix a failing test case. This will give near-complete coverage, and it completely transforms the experience of working in a dynamic language. And yes, I've done some pretty serious refactorings of Ruby code. They're a bit harder than Eclipse refactorings, but there's usually far fewer lines of code, so it balances out. – emk – 2010-04-07T14:18:13.903

4@emk, thanks for that: so basically you're replacing compile-time type checks with test-time human-written test code. Except for the fact that the latter is much more comprehensive, it doesn't sound like a very good tradeoff (more work). But I'll let you know what I think after a few months of Ruby with tests. – Dan Rosenstark – 2010-04-08T08:01:34.290

2@yar, no problem! But even working in static languages, I tend to prefer very comprehensive test suites, because I design my APIs working from the test suites inwards to the actual implementation. So for people who've adopted this style, Ruby is literally no extra work—and we get some cool dynamic features, too. (There are some exceptions to this in my experience, particularly higher-order mathematical code in Haskell, where types and tests are invaluable.) Good luck with Ruby! – emk – 2010-04-10T12:32:29.110


I use the following approach:

class MyClass
  MY_ENUM = [MY_VALUE_1 = 'value1', MY_VALUE_2 = 'value2']

I like it for the following advantages:

  1. It groups values visually as one whole
  2. It does some compilation-time checking (in contrast with just using symbols)
  3. I can easily access the list of all possible values: just MY_ENUM
  4. I can easily access distinct values: MY_VALUE_1
  5. It can have values of any type, not just Symbol

Symbols may be better cause you don't have to write the name of outer class, if you are using it in another class (MyClass::MY_VALUE_1)


Posted 2008-09-16T19:02:09.073

Reputation: 5 524

3I think this is the best answer. The functionality, syntax and minimal code overhead come closest to Java/C#. Also you can nest the definitions even deeper than one level and still recover all values with MyClass::MY_ENUM.flatten. As a side note I would use uppercased names here as is the standard for constants in Ruby. MyClass::MyEnum might be mistaken for a reference to a subclass. – Janosch – 2015-04-29T12:10:09.497

@Janosch, I've updated the names. thanks for suggestion – Alexey – 2015-09-12T08:28:40.880

I'm still a little confused, and the link 410'd (no, not 404). Could you give examples as to how this enum would be used? – Shelvacu – 2015-10-21T17:18:21.837

@Shel, I've updated the answer. hope it helps – Alexey – 2015-10-27T07:57:52.557


If you are using Rails 4.2 or greater you can use Rails enums.

Rails now has enums by default without the need for including any gems.

This is very similar (and more with features) to Java, C++ enums.

Quoted from http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html :

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]

# conversation.update! status: 0
conversation.active? # => true
conversation.status  # => "active"

# conversation.update! status: 1
conversation.archived? # => true
conversation.status    # => "archived"

# conversation.update! status: 1
conversation.status = "archived"

# conversation.update! status: nil
conversation.status = nil
conversation.status.nil? # => true
conversation.status      # => nil


Posted 2008-09-16T19:02:09.073

Reputation: 9 240

4As you said - not useful if the OP is not using Rails (or more accurately the object is not of type ActiveRecord). Just explaining my downvote is all. – Ger – 2015-12-08T20:25:53.823

These are not enums in Ruby, it is an ActiveRecord interface to Enums in your database. Not a generalizable solution that can be applied in any other use-case. – Adam Lassek – 2016-05-09T06:08:54.743

I have aleady mentioned that in my answer. – vedant – 2016-05-13T05:34:21.810

This is the best answer IFF using Rails. – theUtherSide – 2016-11-15T04:10:00.703

I don't like it because it must be stored in a Rails database (to work) and because it allows to create many instances of the Conversation class - I believe it must allow only 1 instance. – prograils – 2017-06-29T09:42:05.030


This is my approach to enums in Ruby. I was going for short and sweet, not necessarily the the most C-like. Any thoughts?

module Kernel
  def enum(values)
    Module.new do |mod|
      values.each_with_index{ |v,i| mod.const_set(v.to_s.capitalize, 2**i) }

      def mod.inspect
        "#{self.name} {#{self.constants.join(', ')}}"

States = enum %w(Draft Published Trashed)
=> States {Draft, Published, Trashed} 

=> 1

=> 2

=> 4

States::Draft | States::Trashed
=> 3


Posted 2008-09-16T19:02:09.073

Reputation: 101


I know it's been a long time since the guy posted this question, but I had the same question and this post didn't give me the answer. I wanted an easy way to see what the number represents, easy comparison, and most of all ActiveRecord support for lookup using the column representing the enum.

I didn't find anything, so I made an awesome implementation called yinum which allowed everything I was looking for. Made ton of specs, so I'm pretty sure it's safe.

Some example features:

COLORS = Enum.new(:COLORS, :red => 1, :green => 2, :blue => 3)
=> COLORS(:red => 1, :green => 2, :blue => 3)
COLORS.red == 1 && COLORS.red == :red
=> true

class Car < ActiveRecord::Base    
  attr_enum :color, :COLORS, :red => 1, :black => 2
car = Car.new
car.color = :red / "red" / 1 / "1"
=> Car::COLORS.red
=> false
=> "SELECT `cars`.* FROM `cars` WHERE `cars`.`color` = 1"
=> true

Oded Niv

Posted 2008-09-16T19:02:09.073

Reputation: 1 105


Check out the ruby-enum gem, https://github.com/dblock/ruby-enum.

class Gender
  include Enum

  Gender.define :MALE, "male"
  Gender.define :FEMALE, "female"



Posted 2008-09-16T19:02:09.073

Reputation: 3 599


If you're worried about typos with symbols, make sure your code raises an exception when you access a value with a non-existent key. You can do this by using fetch rather than []:

my_value = my_hash.fetch(:key)

or by making the hash raise an exception by default if you supply a non-existent key:

my_hash = Hash.new do |hash, key|
  raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"

If the hash already exists, you can add on exception-raising behaviour:

my_hash = Hash[[[1,2]]]
my_hash.default_proc = proc do |hash, key|
  raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"

Normally, you don't have to worry about typo safety with constants. If you misspell a constant name, it'll usually raise an exception.

Andrew Grimm

Posted 2008-09-16T19:02:09.073

Reputation: 43 291

It seems you're advocating emulating enums with hashes, without saying so explicitly. It might be a good idea to edit your answer to say so. (I also currently have a need for something like enums in Ruby, and my first approach to solving it is by using hashes: FOO_VALUES = {missing: 0, something: 1, something_else: 2, ...}. This defines the key symbols missing, something, etc., and also makes them comparable via the associated values.) – Teemu Leisti – 2013-09-10T09:06:44.230

I mean, without saying so at the very start of the answer. – Teemu Leisti – 2013-09-10T09:33:58.990


Perhaps the best lightweight approach would be

module MyConstants
  ABC = Class.new
  DEF = Class.new
  GHI = Class.new

This way values have associated names, as in Java/C#:

=> MyConstants::ABC

To get all values, you can do

=> [:ABC, :DEF, :GHI] 

If you want an enum's ordinal value, you can do

MyConstants.constants.index :GHI
=> 2

Daniel Lubarov

Posted 2008-09-16T19:02:09.073

Reputation: 6 194


Someone went ahead and wrote a ruby gem called Renum. It claims to get the closest Java/C# like behavior. Personally I'm still learning Ruby, and I was a little shocked when I wanted to make a specific class contain a static enum, possibly a hash, that it wasn't exactly easily found via google.


Posted 2008-09-16T19:02:09.073

Reputation: 26 400

I have never needed an enum in Ruby. Symbols and constants are idiomatic and solve the same problems, don't they? – Chuck – 2009-03-04T20:53:36.307

Probably Chuck; but googling for an enum in ruby won't get you that far. It will show you results for people's best attempt at a direct equivalent. Which makes me wonder, maybe there's something nice about having the concept wrapped together. – dlamblin – 2009-03-05T01:33:29.473

@Chuck Symbols and constants don't enforce, e.g., that a value has to be one of a small set of values. – David Moles – 2015-03-20T21:44:15.357


Recently we released a gem that implements Enums in Ruby. In my post you will find the answers on your questions. Also I described there why our implementation is better than existing ones (actually there are many implementations of this feature in Ruby yet as gems).


Posted 2008-09-16T19:02:09.073

Reputation: 1 905


This seems a bit superfluous, but this is a methodology that I have used a few times, especially where I am integrating with xml or some such.

class Profession
  def self.pro_enum
    {:BAKER => 0, 
     :MANAGER => 1, 
     :FIREMAN => 2, 
     :DEV => 3, 
     :VAL => ["BAKER", "MANAGER", "FIREMAN", "DEV"]

Profession.pro_enum[:DEV]      #=>3
Profession.pro_enum[:VAL][1]   #=>MANAGER

This gives me the rigor of a c# enum and it is tied to the model.


Posted 2008-09-16T19:02:09.073

Reputation: 447


Symbols is the ruby way. However, sometimes one need to talk to some C code or something or Java that expose some enum for various things.

module EnumLike

  def EnumLike.server_role
    server_Symb.each{ |e| server_Enum[e]=i; i +=1}
    return server_Symb,server_Enum


This can then be used like this

require 'server_roles'

sSymb, sEnum =EnumLike.server_role()


This is can of course be made abstract and you can roll our own Enum class


Posted 2008-09-16T19:02:09.073

Reputation: 5 919

Are you capitalizing the second word in variables (eg server_Symb) for a particular reason? Unless there's a particular reason, it's idiomatic for variables to be snake_case_with_all_lower_case, and for symbols to be :lower_case. – Andrew Grimm – 2011-03-16T23:03:29.543

1@Andrew; this example were taken from a real world thing and the network protocol documentation used xxx_Yyy, so the code in several languages used the same concept so one could follow changes of specification. – Jonke – 2011-03-17T19:55:49.703

1Code golfing: server_Symb.each_with_index { |e,i| server_Enum[e] = i}. No need for i = 0. – Andrew Grimm – 2011-03-17T21:48:07.770


Another solution is using OpenStruct. Its pretty straight forward and clean.



# bar.rb
require 'ostruct' # not needed when using Rails

# by patching Array you have a simple way of creating a ENUM-style
class Array
   def to_enum(base=0)

class Bar

    MY_ENUM = OpenStruct.new(ONE: 1, TWO: 2, THREE: 3)
    MY_ENUM2 = %w[ONE TWO THREE].to_enum

    def use_enum (value)
        case value
        when MY_ENUM.ONE
            puts "Hello, this is ENUM 1"
        when MY_ENUM.TWO
            puts "Hello, this is ENUM 2"
        when MY_ENUM.THREE
            puts "Hello, this is ENUM 3"
            puts "#{value} not found in ENUM"


# usage
foo = Bar.new    
foo.use_enum 1
foo.use_enum 2
foo.use_enum 9

# put this code in a file 'bar.rb', start IRB and type: load 'bar.rb'


Posted 2008-09-16T19:02:09.073

Reputation: 5 806


It all depends how you use Java or C# enums. How you use it will dictate the solution you'll choose in Ruby.

Try the native Set type, for instance:

>> enum = Set['a', 'b', 'c']
=> #<Set: {"a", "b", "c"}>
>> enum.member? "b"
=> true
>> enum.member? "d"
=> false
>> enum.add? "b"
=> nil
>> enum.add? "d"
=> #<Set: {"a", "b", "c", "d"}>


Posted 2008-09-16T19:02:09.073

Reputation: 11 791

8Why not use symbols Set[:a, :b, :c]? – Dan Rosenstark – 2010-03-11T09:50:38.123

1Much better practice to use symbols here, IMO. – Collin Graves – 2015-07-20T19:40:37.667


I have implemented enums like that

module EnumType

  def self.find_by_id id
    if id.instance_of? String
      id = id.to_i
    values.each do |type|
      if id == type.id
        return type

  def self.values
    [@ENUM_1, @ENUM_2] 

  class Enum
    attr_reader :id, :label

    def initialize id, label
      @id = id
      @label = label

  @ENUM_1 = Enum.new(1, "first")
  @ENUM_2 = Enum.new(2, "second")


then its easy to do operations



enum = EnumType.find_by_id 1


valueArray = EnumType.values


Posted 2008-09-16T19:02:09.073

Reputation: 21


module Status
  BAD  = 13
  GOOD = 24

  def self.to_str(status)
    for sym in self.constants
      if self.const_get(sym) == status
        return sym.to_s


mystatus = Status::GOOD

puts Status::to_str(mystatus)




Posted 2008-09-16T19:02:09.073

Reputation: 372


Sometimes all I need is to be able to fetch enum's value and identify its name similar to java world.

module Enum
     def get_value(str)
     def get_name(sym)

 class Fruits
   include Enum
   APPLE = "Delicious"
   MANGO = "Sweet"

 Fruits.get_value('APPLE') #'Delicious'
 Fruits.get_value('MANGO') # 'Sweet'

 Fruits.get_name(:apple) # 'APPLE'
 Fruits.get_name(:mango) # 'MANGO'

This to me serves the purpose of enum and keeps it very extensible too. You can add more methods to the Enum class and viola get them for free in all the defined enums. for example. get_all_names and stuff like that.


Posted 2008-09-16T19:02:09.073

Reputation: 72


Most people use symbols (that's the :foo_bar syntax). They're sort of unique opaque values. Symbols don't belong to any enum-style type so they're not really a faithful representation of C's enum type but this is pretty much as good as it gets.

Jan Krüger

Posted 2008-09-16T19:02:09.073

Reputation: 12 230


irb(main):016:0> num=[1,2,3,4]
irb(main):017:0> alph=['a','b','c','d']
irb(main):018:0> l_enum=alph.to_enum
irb(main):019:0> s_enum=num.to_enum
irb(main):020:0> loop do
irb(main):021:1* puts "#{s_enum.next} - #{l_enum.next}"
irb(main):022:1> end


1 - a
2 - b
3 - c
4 - d


Posted 2008-09-16T19:02:09.073

Reputation: 11


Another way to mimic an enum with consistent equality handling (shamelessly adopted from Dave Thomas). Allows open enums (much like symbols) and closed (predefined) enums.

class Enum
  def self.new(values = nil)
    enum = Class.new do
      unless values
        def self.const_missing(name)
          const_set(name, new(name))

      def initialize(name)
        @enum_name = name

      def to_s

    if values
      enum.instance_eval do
        values.each { |e| const_set(e, enum.new(e)) }


Genre = Enum.new %w(Gothic Metal) # creates closed enum
Architecture = Enum.new           # creates open enum

Genre::Gothic == Genre::Gothic        # => true
Genre::Gothic != Architecture::Gothic # => true

Daniel Doubleday

Posted 2008-09-16T19:02:09.073

Reputation: 168


Another approach is to use a Ruby class with a hash containing names and values as described in the following RubyFleebie blog post. This allows you to convert easily between values and constants (especially if you add a class method to lookup the name for a given value).

Philippe Monnet

Posted 2008-09-16T19:02:09.073

Reputation: 842


I think the best way to implement enumeration like types is with symbols since the pretty much behave as integer (when it comes to performace, object_id is used to make comparisons ); you don't need to worry about indexing and they look really neat in your code xD


Posted 2008-09-16T19:02:09.073

Reputation: 193


Try the inum. https://github.com/alfa-jpn/inum

class Color < Inum::Base
  define :RED
  define :GREEN
  define :BLUE
Color.parse('blue') # => Color::BLUE
Color.parse(2)      # => Color::GREEN

see more https://github.com/alfa-jpn/inum#usage


Posted 2008-09-16T19:02:09.073

Reputation: 1