iteration over enum in ruby
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?
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:
UserStatus.constants(false).each do |const_name|
p [ const_name, UserStatus.const_get( const_name ) ]
end
#=> :NEW, "new"]
#=> [:OLD, "old"]
#=> [:DELETED, "deleted"]
The use of false
above is needed to prevent you from getting constants defined in superclasses:
class Foo; A = 1; end
class Bar < Foo; B = 1; end
Bar.constants
#=> [:B, :A]
Bar.constants(false)
#=> [:B]
If you are not married to the use of individual constants, you might be interested in creating a frozen Hash of immutable values instead:
class User < ActiveRecord::Base
STATUS = {
:new => 'new',
:old => 'old',
:deleted => 'deleted'
}
STATUS.freeze
STATUS.values.each{ |v| v.freeze }
end
bob.status = User::STATUS[:new]
User::STATUS.each do |name,string|
p [ name, string ]
end
Ruby does not have "enum". Those are constants that you have defined. Given that, you can iterate over constants in a class like this:
#UserStatus.constants returns an array, which we then iterate over
UserStatus.constants.each do |el|
p el
end
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.
class Gender
include Enum
Gender.define :MALE, "male"
Gender.define :FEMALE, "female"
end
And of course
Gender.all
Gender::MALE
精彩评论