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

时间:2015-08-07 02:46:15

标签: ruby enums symbols

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

2 个答案:

答案 0 :(得分:1)

通常我会创建一个包含允许符号的常量数组。如果你想确保它不会改变,你可以冻结它。

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

如果您有许多不同的元素,则可以使用%i()语法:

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

如果你正在使用Rails,那么从4.1版本开始,enum macro可用于ActiveRecord :: Base。

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

Car.new(color: :red)

答案 1 :(得分:0)

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

这可能不适合每个人的需求。我只是想要没有价值的符号。 您可以这样使用它

type = TOKEN_TYPES::CLASS
# => type = :CLASS