【问题标题】:How to map over a nested array如何映射嵌套数组
【发布时间】:2013-07-17 21:16:53
【问题描述】:

我有一个数组:

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

我想遍历每个“单元格”并将值更改为其他值。如何在不展平数组和重新组合的情况下做到这一点。比如:

   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

上面的方法并不完全符合我的想法(随机字母的工作,但每一行的随机字母与最后一行相同,顺序相同)

想法?

【问题讨论】:

    标签: ruby arrays multidimensional-array


    【解决方案1】:

    您根本不需要索引。

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

    如果你想保留每个数组的对象id并改变内容,那么你可以使用replace

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

    【讨论】:

      【解决方案2】:

      我认为以下方法可行:

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

      【讨论】:

        猜你喜欢
        • 2023-01-18
        • 2019-08-13
        • 2021-09-30
        • 2018-03-09
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        相关资源
        最近更新 更多