2

To iterate through the elements in a single dimensional array, I can use

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

Is there any way I to do this for a nested list or a two dimensional array? In this code:

two_d_array = [[1,2], [3,4], [5,6]]
two_d_array.each{|array| puts array}

I wish to get [1, 2], [3, 4], [5, 6] so that I can access each element of the list separately and do some operation on it such as array[1] = "new_value", but it gives 123456 I want to avoid using matrix if possible.

sawa
  • 165,429
  • 45
  • 277
  • 381
Primal Pappachan
  • 25,857
  • 22
  • 67
  • 84

1 Answers1

6

Actually the each block does behave in the way you expect, but the puts command makes it look as though the array has been pre-flattened. If you add an inspect, this becomes clear:

>> two_d_array.each{|array| puts array.inspect}
[1, 2]
[3, 4]
[5, 6]

So the array variable in each iteration will be the nested array element.

Jon M
  • 11,669
  • 3
  • 41
  • 47
  • Or he can also use pp instead of puts – Jasdeep Singh Mar 04 '12 at 05:36
  • I tried two_d_array.each{|array| funct(array)} but the funct doesn't receive individual lists as arguments. – Primal Pappachan Mar 04 '12 at 05:39
  • I'm a little confused - so what is happening to make you say that `funct` is not receiving an array? Might help to edit the question and include a fuller example to illustrate your problem. – Jon M Mar 04 '12 at 05:51
  • @primpop did you get this working in the end? If so please consider marking this answer as accepted! – Jon M Mar 07 '12 at 01:11
  • @JonM I changed'funct' around a bit from the initial one I showed. Anyways, your answer helped in sorting out the problem. Thanks. – Primal Pappachan Mar 07 '12 at 03:51