Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ruby, where do you put related symbols like enum in java?

As I understand from Enums in Ruby question, you use Symbols to stand for something in ruby instead of enums in other languages as java or C#.

When you have enums, you can gather related identifiers in one place as below. You can see from the code that there are three colors available, and that paint method accepts one of those three values.

enum Color {
  Red,
  Yellow,
  Purple
}
public void paint(Color color) {}

how do you document the available values for related symbols in ruby?(:red, :yellow, :purple) Do you have to put it in a comment in the method that uses them, as below?

# allowed colors: :red, :yellow, :purple
def paint(color)
end
like image 350
Yeonho Avatar asked Apr 28 '26 21:04

Yeonho


2 Answers

Usually I create a constant array containing the allowed symbols. You can freeze it if you want to be sure that it won't change.

COLORS = [:red, :green, :blue].freeze

If you have a lot of different elements, you can use the %i() syntax:

COLORS = %i(red green blue yellow purple).freeze

And if you're using Rails, since the 4.1 version there's a enum macro available for ActiveRecord::Base.

class Car < ActiveRecord::Base
  enum color: %i(red green blue yellow purple)
end

Car.new(color: :red)
like image 169
mrodrigues Avatar answered Apr 30 '26 12:04

mrodrigues


module TOKEN_TYPES 

  def self.const_missing(name)
    type = TYPES.find { |e| e == name.to_s.upcase.to_sym }
                    raise "constant not found error" if type.nil?
  return type

  end

# punctuation
TYPES = [:LEFT_PAREN, :RIGHT_PAREN, :LEFT_BRACE, :RIGHT_BRACE,
       :COMMA, :DOT, :SEMICOLON, :SLASH, :BACK_SLASH, :STAR,

# mathematical operators
:OP_PLUS, :OP_MINUS, :OP_MUL, :OP_DIV, :LT, :LE, :EQ, :NE, :GT, :GE, :OP_POW, # ne = <>

# logical operators
:TRUE, :FALSE, :NIL,

# program flow

# errors

# other
:AMPERSAND,

# literals
:NUM, :STRING, :SYM, :IDENTIFIER, :CONSTANT,

# keywords
:CLASS, :MODULE, :BEGIN, :END, :IF, :ELSE, :IF, :UNLESS, :DO, :WHILE, :FOR, :UNTIL,
:NEXT, :SKIP, :BREAK, :RETURN, :DEF, :ENFORCE, :INCLUDE, :EXTEND,

:EOF]
end

This may not suit everybody's needs. I just wanted symbols without value. You can use it like this

type = TOKEN_TYPES::CLASS
# => type = :CLASS
like image 44
von spotz Avatar answered Apr 30 '26 12:04

von spotz