Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and iterating a 2d array in Ruby

I have very little knowledge about Ruby and cant find a way to create 2d array. Can anyone provide me some snippets or information to get me started?

like image 497
Alex Avatar asked Oct 13 '12 17:10

Alex


People also ask

What is a 2D array Ruby?

A 2D array would be a plane with rows and columns. The first pair of indexing brackets refers to the row number and the second refers to the column number. puts arr2d[0][1] //this would print the element at 0th row and 1st column.

What does .each do in Ruby?

each is just another method on an object. That means that if you want to iterate over an array with each , you're calling the each method on that array object. It takes a list as it's first argument and a block as the second argument.


1 Answers

a = [[1, 2], [3, 4]]
a.each do |sub|
  sub.each do |int|
    puts int
  end
end
# Output:
#   1
#   2
#   3
#   4

or:

a = [[1, 2], [3, 4]]
a.each do |(x, y)|
  puts x + y
end
# Output:
#   3
#   7
like image 132
simonmenke Avatar answered Oct 13 '22 01:10

simonmenke