Rohan Panchal
Rohan Panchal

Reputation: 1266

Ruby module/enum retrieves odd values

Trying to build an enum for ruby so I can retrieve int values for the corresponding enum value.

My module looks like:

module DataType
  STRING  = 1,
  NUMBER  = 2,
  BOOLEAN = 3,
  OBJECT  = 4,
  DATA    = 5,
  FILE    = 6,
  DATE    = 7,
  ARRAY   = 8
end

If I call this with any value other than String,

DataType::Number

It returns

 2... 3, 4, 5, 6, 7, 8, 

But if I call

DataType::String

It returns

[1, 2, 3, 4, 5, 6, 7, 8]

How and why is DataType::String returning an array of all the enum values?

Upvotes: 2

Views: 240

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You declare constant by comma:

module DataType
  STRING  = 1,
  NUMBER  = 2,
  ...........
end

DataType::Number second position in module and return value from second position, you need this instead:

module DataType
  STRING  = 1
  NUMBER  = 2
  BOOLEAN = 3
  ..........
end

Now DataType::Number return 2. and return all:

=> DataType.constants.map { |x| Hash[x, DataType.const_get(x)] }
=> [{:STRING=>1}, {:NUMBER=>2}, {:BOOLEAN=>3}, {:OBJECT=>4}, {:DATA=>5}, {:FILE=>6}, {:DATE=>7}, {:ARRAY=>8}]

For help Module#constants and Module#const_get.

Upvotes: 3

Related Questions