How to downcase an Enum member name?

Me, again ;-)

enum Foo
  I8
end

I can’t rename I8 to i8, this is forbiden
I can’t either

enum Foo
  I8
  def to_s
   "#{self}".downcase
  end
end

That leads to an infinite loop

So we have Enum.names but no .name() on each member exepted the stock to_s ?

I’m pretty sure Enum members have to start with an uppercase letter. You shouldn’t override to_s, but instead use to_s(io : IO) and append to the io. You can also do this for inspect(io : IO), if that fits your bill better. Or you can just define another method that returns self.to_s.downcase (I used this pattern myself).

Except you have to override Enum#to_s, because it is the IO overload that forwards to it, not the other way round.

Personally I wish there is a way to override specific members’ names without having to override either.

2 Likes

The simplest way to do it:

enum Numbers
  One
  Two
  Three

  def to_s
    super.downcase
  end
end

The most runtime-efficient way, avoids the heap allocation:

enum Numbers
  One
  Two
  Three

  def to_s
    {% begin %}
      case self
      {% for member in @type.constants %}
        in .{{ member.id.downcase }}?
          "{{ member.id.downcase }}"
      {% end %}
      end
    {% end %}
  end
end
3 Likes

Would work out well if you could annotate constants, then could do something like JSON::Field.

1 Like

Great line. Thanks