# How can I define UNION in ruby?

**URL:** <https://www.ruby-forum.com/t/how-can-i-define-union-in-ruby/112084>\
**Category:** Ruby\
**Created:** [August 15, 2007, 2:50am UTC](https://www.ruby-forum.com/t/how-can-i-define-union-in-ruby/112084 "2007-08-15T02:50:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Zhan\_feng\_W](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/a88e57/32.png) [@Zhan\_feng\_W](https://www.ruby-forum.com/u/Zhan_feng_W)\
**Post date:** [August 15, 2007, 2:50am UTC](https://www.ruby-forum.com/t/how-can-i-define-union-in-ruby/112084/1 "2007-08-15T02:50:28Z")

</div>

Hi,friends,  
I’d like to know how can I define UNION in ruby?  
e.g.  
In C, I have a UNION as following:  
union ID\_OCT{  
struct ID\_BIT{  
unsigned class:2; /_b8,b7_/  
unsigned if\_prim:1; /_b6,0–primitive_/  
unsigned tag\_no:5;/_if \>=31,second byte give tag\_no base  
128_/  
}id;  
unsigned char c;  
}rid;

How can I define this in Ruby?

Which document specified this?  
Thanks

---

<div class="post-metadata">

**Author:** ![Zhan\_feng\_W](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/a88e57/32.png) [@Zhan\_feng\_W](https://www.ruby-forum.com/u/Zhan_feng_W)\
**Post date:** [August 15, 2007, 3:05am UTC](https://www.ruby-forum.com/t/how-can-i-define-union-in-ruby/112084/2 "2007-08-15T03:05:25Z")

</div>

On 8/14/07, Zhan feng Wang [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 128\*/  
> }id;  
> unsigned char c;  
> }rid;

Ruby has no union construct. Depending on what you are trying to  
achieve,  
there are various options. If you want a union because you need a  
variable  
to be able to have values of different types, then you need do nothing  
special since ruby is dynamically typed. If you want a union because  
you’d  
like to have mutiple “views” of the same sequence of bytes or bits,  
check  
out Array#pack and String#unpack, as well as bitstruct  
[http://raa.ruby-lang.org/project/bit-struct/](http://raa.ruby-lang.org/project/bit-struct/)

How can I define this in Ruby?
