我只想知道在Ruby中模拟C#样式枚举的最佳方法.
它不完全相同,但我经常会为这种事情构建一个哈希:
STATES = {:open => 1, :closed => 2, :max => 3, :min => 4}.freeze()
冻结哈希使我不会意外地修改其内容.
此外,如果您想在访问不存在的内容时引发错误,可以使用defualt Proc来执行此操作:
STATES = Hash.new { |hash, key| raise NameError, "#{key} is not allowed" } STATES.merge!({:open => 1, :closed => 2, :max => 3, :min => 4}).freeze() STATES[:other] # raises NameError
具体来说,我希望能够在给定一些变量的情况下对这组值执行逻辑测试.示例是窗口的状态:"最小化,最大化,关闭,打开"
如果你需要枚举映射到值(例如,你需要最小化等于0,最大化等于100等)我会使用符号散列值,如下所示:
WINDOW_STATES = { :minimized => 0, :maximized => 100 }.freeze
冻结(就像nate所说)会阻止你在将来意外破坏事物.这样做可以检查某些内容是否有效
WINDOW_STATES.keys.include?(window_state)
或者,如果您不需要任何值,只需要检查'membership',那么数组就可以了
WINDOW_STATES = [:minimized, :maximized].freeze
像这样使用它
WINDOW_STATES.include?(window_state)
如果您的键将成为字符串(例如RoR应用程序中的'state'字段),那么您可以使用字符串数组.我在许多rails应用程序中一直这样做.
WINDOW_STATES = %w(minimized maximized open closed).freeze
这几乎是rails validates_inclusion_of
验证器专门用于:-)
我不喜欢打字包括?所有的时间,所以我有这个(由于.in?(1,2,3)的情况,它只是复杂的:
class Object # Lets us write array.include?(x) the other way round # Also accepts multiple args, so we can do 2.in?( 1,2,3 ) without bothering with arrays def in?( *args ) # if we have 1 arg, and it is a collection, act as if it were passed as a single value, UNLESS we are an array ourselves. # The mismatch between checking for respond_to on the args vs checking for self.kind_of?Array is deliberate, otherwise # arrays of strings break and ranges don't work right args.length == 1 && args.first.respond_to?(:include?) && !self.kind_of?(Array) ? args.first.include?( self ) : args.include?( self ) end end end
这可以让你输入
window_state.in? WINDOW_STATES