Array indices

Is there a way to set the indice on an array,
i.e.

Instead of:

myarray = [1,2,3,4,5]
myarray[1] =2
myarray[4]=5

myarray[A]=1

I know this can be done using hashes but was not sure with arrays

Stuart

On Jun 25, 2006, at 17:50, Dark A. wrote:

I know this can be done using hashes but was not sure with arrays

Check the docs for the Array class. I know there’s a method which
does this (several variations on it, actually), but I can’t remember
what it’s called.

matthew smillie.

On Jun 25, 2006, at 17:50, Dark A. wrote:

I know this can be done using hashes but was not sure with arrays

Negate that last answer - I misunderstood. Sorry.

Anyway, array indices are always integers. As long as A references
or evaluates to an integer, no problem:

A = 3
myarray = []
myarray[A] = “foo”
=> [nil, nil, nil, “foo”]

matthew smillie.

On Mon, 26 Jun 2006, Dark A. wrote:

I know this can be done using hashes but was not sure with arrays

Stuart

harp:~ > cat a.rb

gem install arrayfields

require ‘rubygems’
require ‘arrayfields’

myarray = [1,2,3,4,5]
myarray.fields = [‘A’,‘B’,‘C’,‘D’,‘E’]

p myarray[‘A’]

harp:~ > ruby a.rb
1

-a

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs