如何在Ruby中使用C#样式枚举? [英] How can I use C# style enumerations in Ruby?

查看:85
本文介绍了如何在Ruby中使用C#样式枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道在Ruby中模拟C#样式枚举的最佳方法。

I just want to know the best way to emulate a C# style enumeration in Ruby.

推荐答案


具体来说,我希望能够对给定变量的一组值进行逻辑测试。例如窗口状态:最小化,最大化,关闭,打开

Specifically, I would like to be able to perform logical tests against the set of values given some variable. Example would be the state of a window: "minimized, maximized, closed, open"

如果您需要枚举来映射到值(例如,您需要将其最小化为等于0,最大为等于100,依此类推)我将使用符号的哈希值作为值,例如:

If you need the enumerations to map to values (eg, you need minimized to equal 0, maximised to equal 100, etc) I'd use a hash of symbols to values, like this:

WINDOW_STATES = { :minimized => 0, :maximized => 100 }.freeze

冻结(如nate所说)可以防止您将来意外破碎东西。
您可以通过执行以下操作来检查某项是否有效

The freeze (like nate says) stops you from breaking things in future by accident. You can check if something is valid by doing this

WINDOW_STATES.keys.include?(window_state)

或者,如果您不需要任何值,只需要检查 membership,那么数组就可以了

Alternatively, if you don't need any values, and just need to check 'membership' then an array is fine

WINDOW_STATES = [:minimized, :maximized].freeze

使用它像这样

WINDOW_STATES.include?(window_state)

如果键将是字符串(例如RoR应用程序中的 state字段),则可以使用字符串数组。我一直在许多Rails应用程序中都这样做。

If your keys are going to be strings (like for example a 'state' field in a RoR app), then you can use an array of strings. I do this ALL THE TIME in many of our rails apps.

WINDOW_STATES = %w(minimized maximized open closed).freeze

这几乎是Rails validates_inclusion_of 验证程序专门用于:-)

This is pretty much what rails validates_inclusion_of validator is purpose built for :-)

我不喜欢键入include?一直如此,所以我有这个问题(只是因为.in?(1、2、3)的情况而变得复杂:

I don't like typing include? all the time, so I have this (it's only complicated because of the .in?(1, 2, 3) case:

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

这篇关于如何在Ruby中使用C#样式枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆