Class: Union
- Inherits:
-
Struct
- Object
- Struct
- Union
- Defined in:
- lib/union.rb
Overview
The Union class provides an analogue of a C union. Only one member of a Union object can be set to a non-nil value at a time.
Constant Summary collapse
- VERSION =
The version of the union library
'1.0.3'
Instance Method Summary collapse
-
#[]=(symbol, value) ⇒ Object
Identical to Struct attribute assignment, except that setting one instance variable sets all other instance variables to nil.
-
#initialize ⇒ Union
constructor
Creates and returns a new Union.
Constructor Details
#initialize ⇒ Union
Creates and returns a new Union. Unlike Struct::Class.new, this does not take any arguments. You must assign attributes individually.
Union.new('Human', :name, :age)
h = Union::Human.new
h.name = 'Daniel' # => #<struct Union::Human name="Daniel", age=nil>
h.age = 38 # => #<struct Union::Human name=nil, age=38>
– The semantics of Union.new(arg1, arg2, …) would be non-sensical. Which attribute should be set while the rest are ignored? The first one or the last one? I decided to disallow it altogether.
21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/union.rb', line 21 def initialize super members.each{ |attribute| m = %Q{ def #{attribute}=(value) self['#{attribute}'] = value end } instance_eval(m) } end |
Instance Method Details
#[]=(symbol, value) ⇒ Object
Identical to Struct attribute assignment, except that setting one instance variable sets all other instance variables to nil. Also, you cannot use a numeric index. You must use a string or symbol.
Union.new('Human', :name, :age)
h = Union::Human.new
h[:name] = 'Daniel' # => #<struct Union::Human name="Daniel", age=nil>
h[:age] = 38 # => #<struct Union::Human name=nil, age=38>
43 44 45 46 |
# File 'lib/union.rb', line 43 def []=(symbol, value) super(symbol, value) members.each{ |m| super(m, nil) unless m.to_s == symbol.to_s } end |