Forum: Ruby on Rails multi dimensional array

E03adaf0f9c0ec177d81e4fe82ed973c?d=identicon&s=25 Narayana Karthick (narayana)
on 2006-08-02 15:42

how to implement multi dimensional array in ruby
in ruby multi dimension array look like tree structure
plz help me & explain with code
have a pleasant day
thx
narayana
D0cd6b10e01bacb976b3b815a9c660bc?d=identicon&s=25 Alex Wayne (Guest)
on 2006-08-03 00:57
Narayana Karthik wrote:
>
>
> how to implement multi dimensional array in ruby
> in ruby multi dimension array look like tree structure
> plz help me & explain with code
> have a pleasant day
> thx
> narayana

While a "true" multi-dimensional array is not in the standard ruby
library, you can fake it by having arrays of array pretty easily.

def multiplaction_table(limit)
  output = []
  limit.times do |x|
    output[x] = []
    limit.times do |y|
      output[x][y] = x * y
    end
  end

  output
end

result = multiplaction_table(10)
result[5][8] #=> 40
result[6][6] #=> 36
result[2][3] #=> 6
D461d550e622d94f0776c40c31018399?d=identicon&s=25 linux user (Guest)
on 2006-08-03 12:40
(Received via mailing list)
Karthik

below are two examples first is for 2 dimensional array and second for 3
dimension

irb(main):001:0> mar = [[1,2],[3,4],[5,6]] #this creates 2 dimensional
array
called mar
=> [[1, 2], [3, 4], [5, 6]]
irb(main):002:0> mar[1][0] #to access value 3 we have to access 2nd
element
of mar which is an array and then 1st element of that array
=> 3
irb(main):003:0> mar3 = [[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]]]
#
this creates 3 dimensional array mar3
=> [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]
irb(main):004:0> mar3[2][1][1] # value 12 is in 3rd element of mar3, in
it
its the 2nd element is [11,12] and in it 2nd element is value 12
=> 12
irb(main):005:0>

I hope this helps
-daya
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.