Genric List in Ruby

Hi in newbie to Ruby …But i have experience in C#…

I want to achieve Generic List in that is there in C# in Ruby.
What i want is as follows:

Class Thing
string name;
string id;

Class Shelf
List lstthing = new List;

Above is C# code; How can I write same in Ruby…

Please help need it urgent!!!

Thanks in Advance

Ruby is dynamically typed. Even the basic Array type can contain values
that are of any type whatsoever, so it is already a generic list which
even more generic and flexible than the generic lists you can create in
most languages like C# and Java. It is perfectly legal to make an array

[ “a”, 1, :b,]

where each element has a completely different type. I think it will take
while for dynamic typing to sink in for someone like you who is used to
static types, but do take the time to understand it because it is what
makes Ruby what it is.

Also read about duck typing:

From my iPhone


On Thu, Nov 24, 2011 at 04:29, Sagar V. [email protected]

Class Thing
string name;
string id;

Class Shelf
List lstthing = new List;

Above is C# code; How can I write same in Ruby…

It seems to me that the previous answers were essentially “Ruby lists
are generic, what’s wrong?”.

However, I interpret your question as: “how do I make a list NOT
generic, using what some other languages call ‘generics’ because the
rest of it is generic, so that a Shelf can ONLY contain Things?”.
Is that what you mean?

If so, you can’t do that quite so easily, but you can extend or wrap
some container class. You’d have to tell it what class of things you
want to put in, or maybe some other test. For your immediate needs,
maybe something like:

class Thing

insert guts of class Thing here


simple array wrapper

class Shelf

def initialize
@myArray =

def add thang
raise ‘Error: Shelves can only contain Things’ if ! thang.is_a?
@myArray.push thang

insert here similar calls for any other methods you want that add


insert here any calls you want to remove things from it, look at

the shelf, etc.;

some of it could probably be automagically delegated to Array with

one def

of method_missing. Could probably do that with everything except

the calls that insert things…


Long-term, if I needed that kind of thing a lot, I’d be tempted to
make a generic wrapper and pass it a block, and say that only things
that make that block return true would get inserted, with everything
else causing an exception. However, that sounds to me like the kind
of thing that might be needed often enough that someone might have
already made a gem for it. Anybody out there know offhand?