Skip to content

Instantly share code, notes, and snippets.

@pietromoro
Last active July 30, 2020 13:27
Show Gist options
  • Select an option

  • Save pietromoro/cb830491a2a32ea9313bb3953129796e to your computer and use it in GitHub Desktop.

Select an option

Save pietromoro/cb830491a2a32ea9313bb3953129796e to your computer and use it in GitHub Desktop.
Quick ruby enum
module Kernel
def enum(values)
Module.new do |mod|
values.each_with_index{ |v,i| mod.const_set(v.to_s.capitalize, 2**i) }
def mod.inspect
"#{self.name} {#{self.constants.join(', ')}}"
end
end
end
end
@pietromoro
Copy link
Author

Usage

State = enum %w(CONNECT CONNECTING DISCONNECT)
# => State{CONNECT, CONNECTING, DISCONNECT}

State::CONNECT
# => 1

State::CONNECT | Sate::CONNECTING
# => 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment