开发者

Best way of emulating enum in Ruby? (part two)

开发者 https://www.devze.com 2022-12-15 06:39 出处:网络
I\'m new to Ruby so forgive me if this is something obvious.. I\'ve made a class like so class Element attr_accessor :type

I'm new to Ruby so forgive me if this is something obvious..

I've made a class like so

class Element
  attr_accessor :type
  :type_integer
  :type_string
end

(this is really just an example, not actual code)

Well, I've read Enums in Ruby and I'd prefer to go the Symbols route of having something like enumerations in other languages. I have a problem though, ho开发者_如何学编程w can I keep my global scope clear while implementing this. What I'm wanting to be able to do is something like

e=Element.new
e.type=Element.type_integer

or something pretty simple and straight forward like that.


Symbols don't do anything to the global (or any other) scope (i.e. no variables or constants or anything else gets defined when you use symbols), so I guess the answer is: just use symbols and the global scope will be kept clear.

If you want to use e.type=Element.type_integer, while still using symbols, you could do:

class Element
  def self.type_integer
    :type_integer
  end
end

Although I fail to see the upside vs. just using e.type = :type_integer directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消