简体   繁体   English

如何映射嵌套数组

[英]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? 思考?

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 . 如果要保留每个数组的对象ID并更改内容,则可以使用replace

my_array.each{|row| row.replace(row.map{random_letter})}

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM