0

I have an array of arrays:

array = [
          [1,2,3],
          [4,5,6],
          [7,8,9]
        ]

How would I iterate over each array and print them out individually, without using map?

Something like

array.each do |a|  
  puts a
end

> [1,2,3]
> [4,5,6]
> [7,8,9]
1
  • Replace puts a with another .each call, this time with a.each instead of array.each. Commented Oct 28, 2015 at 18:58

1 Answer 1

3

The to_s method of Array gives a string representation.

array = [ [1,2,3],
          [4,5,6],
          [7,8,9]]

array.each do |a|  
  puts a.to_s  #or just: p a
end

Output

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Sign up to request clarification or add additional context in comments.

2 Comments

I initially missed your comment, #or just: p a. That would seem to be the better (and more conventional) way, as it does not require the creation of a new object.
@CarySwoveland p just calls inspect. AFAIK it creates a new String.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.