You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
One use case I have for enums is that I want to use them in case statements. A nice feature in Rust is exhaustive matching. Obviously, this doesn't work in native Ruby because of the missing types. However, in ruby-enum, it can work, because we have the information about which cases should be handled.
A possible drawback of this is that such a check adds additional steps to each call of the case statement and makes the runtime of the code slower.
I implemented a quick version of this in a project of mine and would be happy to contribute it to this project. A default/else block could be added as well.
Let me know what you think about it :)
### Adds a method to an enum class that allows for exhaustive matching on a value.## @example# class Color# include Ruby::Enum# include Ruby::Enum::Ecase## define :RED, :red# define :GREEN, :green# define :BLUE, :blue# end## Color.ecase(Color::RED, {# [Color::RED, Color::GREEN] => -> { puts "red or green" },# Color::BLUE => -> { puts "blue" },# })moduleRuby::Enum::Ecasedefself.included(klass)klass.extend(ClassMethods)end### @see Ruby::Enum::EcasemoduleClassMethodsclassValuesNotDefinedError < StandardErrorendclassNotAllCasesHandledError < StandardErrorenddefecase(value,cases)validate_cases(cases)cases.eachdo |values,block|
values=[values]unlessvalues.is_a?(Array)block.callifvalues.include?(value)endendprivatedefvalidate_cases(cases)all_values=cases.keys.flattensuperfluous_values=all_values - valuesmissing_values=values - all_valuesifsuperfluous_values.any?raiseValuesNotDefinedError,"Value(s) not defined: #{superfluous_values.join(", ")}"endifmissing_values.any?# rubocop:disable Style/GuardClauseraiseNotAllCasesHandledError,"Not all cases handled: #{missing_values.join(", ")}"endendendend
The text was updated successfully, but these errors were encountered:
@dblock Thanks for making this gem! :)
One use case I have for enums is that I want to use them in case statements. A nice feature in Rust is exhaustive matching. Obviously, this doesn't work in native Ruby because of the missing types. However, in ruby-enum, it can work, because we have the information about which cases should be handled.
A possible drawback of this is that such a check adds additional steps to each call of the case statement and makes the runtime of the code slower.
I implemented a quick version of this in a project of mine and would be happy to contribute it to this project. A default/else block could be added as well.
Let me know what you think about it :)
The text was updated successfully, but these errors were encountered: