gpt4 book ai didi

ruby - 如何映射嵌套数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:52 25 4
gpt4 key购买 nike

我有一个数组:

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

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

想法?

最佳答案

你根本不需要索引。

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

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

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

关于ruby - 如何映射嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com