-4

I have an array a=[0,1,2].

Now I want to add a new element to A[0] and make it a[0]=[0]

I want to do use a[0].push(0), however, I have to define a[0] as an array, so my code will be something like:

a=[0,1,2]
a[0]=[]
for i in 1..100; do a[0].push(i); end

Is there an easy way where I do not need to define a[0] as an array?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user3477465
  • 183
  • 2
  • 2
  • 6
  • What do you want the final array to look like? – matt Jul 21 '14 at 01:55
  • a=[Array(1..100), 1, 2] – nishu Jul 21 '14 at 05:32
  • If you don't care about order*, you can use `Hash`. `h = Hash.new {|hash, key| hash[key] =[] }` - after each access (for example: `h[0]`) Ruby should create new array. You can then just use it like you use to do: `h[432].push 123`. *Hashes starting from, as fair I remember, the Ruby 1.93 are ordered by date of creation (`h = Hash.new {|hash, key| hash[key] =[] }; h[1]; h[0]` will be ordered: `h.keys # => [1, 0]`) – Darek Nędza Jul 21 '14 at 07:50
  • `a = [0,1,2]; a[0]=[]; ` will make your array into `[[], 2, 3]` so why not start with `a = [[], [], []]` or with `Array.new(3) { Array.new }`? And `a=[1,2,3]; a[0] # 1` is a number. You cannot* push anything to the number. You should use a *collections* like hash or array for that. As fair I know, Ruby is *bad* at arrays. It has only 1-dimensional arrays. However Ruby's arrays can have another object like array in it, and that's pretty close to multi-dimensional arrays. ps. sorry for this messy comments, but SO has limits for comments. *with metaprogramming you can but it's hard – Darek Nędza Jul 21 '14 at 08:08

2 Answers2

2

You could use the ruby Matrix class (http://www.ruby-doc.org/stdlib-2.0/libdoc/matrix/rdoc/Matrix.html). Note that after construction, the matrix is immutable, but you can simply define a cell setter like:

 class Matrix
   def []=(i, j, x)
     @rows[i][j] = x
   end
 end
jshort
  • 1,006
  • 8
  • 23
1

I can't work out what array you are trying to end up with. Do you mean something like

a = [0,1,2]
a[0] = Array(1..100)
matt
  • 515,959
  • 87
  • 875
  • 1,141