Alex Young
8/25/2006 7:40:00 AM
Graham Wideman wrote:
> Folks:
>
> I'm new to Ruby, though not to programming in general. So I'm looking around
> for some of the mechanisms I'm used to finding, and one of them is an
> apparatus for Collections (as for example used in C++, OP, VB etc).
>
> I'm hoping that someone can point me in the right direction as to where this
> functionality can be found, or failing that suggest the most advantageous
> starting point to create it based on more primitive classes.
You can get away with just using an Array for almost all of this.
> Main features:
>
> 1. The contained objects are user-defined types having multiple fields (data
> members). This in itself seems no problem for Ruby.
> 2. Order/Retrieve by index. The collection should stay ordered by insertion
> order and support retrieval by integer index. (Sorted collection is a
> separate issue, of course.)
> 3. Insert/Append/Remove/Delete. (List behavior) Allow appending (at end) or
> inserting at arbitrary location, and removal or deletion of arbitrary
> members.
> 4. Find by key: (Dictionary behavior etc) Ability to retrieve member objects
> by supplying a value to match against one of the object's fields. Often this
> is simple a Name field on each object, which functions as a key, but at
> other times one might want lookup based on some other field or fields.
None of these are a problem for Array:
a = [{:a => 1, :b => 2}, {:c => 4, :d => 5}]
a[1] # => {:c=>4, :d=>5}
a << {:e => 6, :f => 7}
# => [{:b=>2, :a=>1}, {:c=>4, :d=>5}, {:e=>6, :f=>7}]
a.select {|x| x[:c] == 4} # => [{:c=>4, :d=>5}]
b = [1,2,3,4]
b.insert(2,5) # => [1, 2, 5, 3, 4]
> So far I've read plenty that seems related: arrays, hashes, Enumerable, and
> several related chapters in PickAxe and Ruby for Rails. Although
> "collections" are mentioned in many of these sources, I've not yet hit on a
> treatment of the ruby way for the Collection basics described above (eg: R
> on R's Collection chapter's description of "insert" is simply replacing the
> Nth element of an array).
If so, that's simply wrong. Array#insert(n, element) makes the inserted
element the n'th and pushes everything after it along one.
--
Alex