Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map over a nested array

I have an array:

my_array = [[1,2,3,4],
            [5,6,7,8],
            [9,10,11,12]]

I want to iterate over each "cell" and change the value to something else. How can I do this without flattening the array and recomposing. Something like:

   my_array.each_with_index do |row, row_index|
      row.each_with_index do |cell, col_index|
        my_array[row_index][col_index] = random_letter
      end
    end

The above method doesn't exactly turn out how I would think (the random letter's work, but each row has the same random letters as the last row, in the same order)

Thoughts?

like image 716
Steven Harlow Avatar asked Jul 18 '13 18:07

Steven Harlow


2 Answers

You don't need indexing at all.

my_array.map{|row| row.map{random_letter}}

If you want to retain the object id of each array and change the content, then you can use replace.

my_array.each{|row| row.replace(row.map{random_letter})}
like image 60
sawa Avatar answered Sep 18 '22 11:09

sawa


I think the below will work:

my_array.map{|ar| ar.map{ "random number" } }


my_array = [[1,2,3,4],
        [5,6,7,8],
        [9,10,11,12]]
my_array.map{|ar| ar.map{ rand(100...400) }}
# => [[345, 264, 194, 157], [325, 117, 144, 149], [303, 228, 252, 199]]
like image 24
Arup Rakshit Avatar answered Sep 22 '22 11:09

Arup Rakshit