Crystal: Make it possible to have numbers as enum members

Created on 3 Apr 2019  路  5Comments  路  Source: crystal-lang/crystal

I think it should be possible to use numbers as enum members.
The usecase is keyboard keys.
It would be really nice if I could put all the keyboard keys in one enum so one can do if pressed? Key::W, if pressed? Key::1 etc. however currently you get this error when having numbers in enums:

Syntax error in eval:2: unexpected token: 1

I don't see any reason why it shouldn't be possible to use numbers as enum members.

Currently the only way (besides strings which would be the worst solution because they are slow) are symbols, so e.g. :"2" (unfortunately :2 doesn't work).
I would have to make a huge case for all the keys. Sure, it can be generated with macros but this whole run-time case would still be much slower compared to just using an enum.

And also as far as I know in the future symbols will (hopefully, besides the enum argument symbols) be removed. Then I would have to go an even worse way, strings.

Most helpful comment

I don't see any reason why it shouldn't be possible to use numbers as enum members.

Here is one: enum members are type identifiers, and type identifiers must start with an uppercase letter.

All 5 comments

I'm not against your proposal, but as a workaround you could have Key::Num1

Yeah as a workaround something like this (or Key::One) probably works but for the long term I would prefer not having to write so much just for one number.

I don't see any reason why it shouldn't be possible to use numbers as enum members.

Here is one: enum members are type identifiers, and type identifiers must start with an uppercase letter.

I thought it's about convieniency and not about strictly following rules like this. There's no advantage in doing that.
I would understand this when I talk about the naming of structs, classes etc. because naming them after numbers is obviously very confusing. But enum members cannot be called without having EnumName:: before it (or passing :"1" to an enum argument but that wouldn't clash with anything). So they are always encapsulated in a namespace and so there's no clash with actual integers. Enum's can't be includeded either.

However I realized that there could be a clash here because this compiles:

enum E
  A
  B
  C

  def self.hello
    puts A
  end
end

E.hello
Was this page helpful?
0 / 5 - 0 ratings