转换2d数组的元素

时间:2013-03-21 20:33:41

标签: ruby arrays type-conversion

我有以下3x3阵列:

grid = [["1","2","3"],["4","5","6"],["7","8","9"]]

我想将每个数字从String转换为Fixnum。我试过了:

grid.each{ |thing| thing.each { |subthing| subthing = subthing.to_i }}

但是,puts grid[0][0].class仍会输出String

1 个答案:

答案 0 :(得分:2)

each只是遍历每个值,它不会更改内容。尝试使用map

foo = grid.map{ |a| a.map(&:to_i) }  # foo => [[1,2,3,],[4,5,6],[7,8,9]], but grid is still the original

如果您想更新网格:

grid.each { |a| a.map!(&:to_i) }