ruby 中枚举的迭代
我有以下带有枚举(UserStatus)的 ruby 类(user.rd):
class User< ActiveRecord::Base
end
class UserStatus
NEW = "new"
OLD = "old"
DELETED = "deleted"
end
有没有办法可以迭代所有枚举值?
i have the following ruby class (user.rd) that has an enum (UserStatus):
class User< ActiveRecord::Base
end
class UserStatus
NEW = "new"
OLD = "old"
DELETED = "deleted"
end
is there a way i can iterate over all the enum values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在那里创建的内容称为“常量”,而不是枚举。正如 Zabba 所说,“Ruby 没有‘enum’。”如果你必须保留这个数据结构,如果你已经在代码中使用了常量,那么你可以像这样迭代它们
:需要上面的
false
来防止您获取超类中定义的常量:如果您不习惯使用单个常量,您可能有兴趣创建不可变值的冻结哈希:
What you have created there are called 'constants', not enumerations. As Zabba said, "Ruby does not have 'enum'." If you must keep this data structure, if you are already using the constants in your code, then you can iterate them like so:
The use of
false
above is needed to prevent you from getting constants defined in superclasses:If you are not married to the use of individual constants, you might be interested in creating a frozen Hash of immutable values instead:
Ruby 没有“枚举”。这些是您定义的常量。
鉴于此,您可以像这样迭代类中的常量:
Ruby does not have "enum". Those are constants that you have defined.
Given that, you can iterate over constants in a class like this:
看看这个: http://code.dblock.org/ShowPost.aspx?id=184 (比 http://www.rubyfleebie.com/enumerations-and- 略有改进红宝石/)。让您编写以下内容。
当然还有
Look at this: http://code.dblock.org/ShowPost.aspx?id=184 (slight improvement over http://www.rubyfleebie.com/enumerations-and-ruby/). Lets you write the following.
And of course