如何用字符串替换多维数组中的整数

时间:2018-12-24 03:10:53

标签: ruby multidimensional-array

我正在生成PDF格式的表格。有一个整数和字符串的多维数组,我有输入。如果数组的值等于输入,则将值替换为'O',否则将替换为'X'。我想用'x'替换其他值。我要打印:

[a][b][c][d]

[ ][O][X][X]

[ ][X][X][X]

有人帮忙吗?我的代码是:

n = 0
Array = [["a","b","c", "d"]] +
[[" "]+[n,n+1,n+2].map{ |n| n + 1 }] + 
[[" "]+[n+3,n+4,n+5].map { |n| n + 1 }]

Array.collect! do |i| 
    if i.include?(1) #assume, input is 1
        i[i.index(1)] = 'X'; i
    else
        i
    end
end

结果:

[a][b][c][d]

[ ][X][2][3]

[ ][4][5][6]

2 个答案:

答案 0 :(得分:0)

这是您如何遍历数组多维的方法,从您的样本中是数组的二维(x,y) 我用arr1替换了数组名

n = 0
arr1 = [["a","b","c", "d"]] +
[[" "]+[n,n+1,n+2].map{ |n| n + 1 }] + 
[[" "]+[n+3,n+4,n+5].map { |n| n + 1 }]

# this is how you replace
arr1.each_with_index do |x, xi|
  x.each_with_index do |y, yi|
    if y.is_a? Integer
      x[yi] = 'X'
    end
  end
end

# this is how you check the result
arr1.each_with_index do |x, xi|
  x.each_with_index do |y, yi|
    puts "element [#{xi}, #{yi}] is #{y}"
  end
end

这是输出

element [0, 0] is a
element [0, 1] is b
element [0, 2] is c
element [0, 3] is d
element [1, 0] is
element [1, 1] is X
element [1, 2] is X
element [1, 3] is X
element [2, 0] is
element [2, 1] is X
element [2, 2] is X
element [2, 3] is X

答案 1 :(得分:0)

这会将所有整数替换为'X'并返回所需的数组。

n = 0
Array = [["a","b","c", "d"]] +
[[" "]+[n,n+1,n+2].map{ |n| n + 1 }] + 
[[" "]+[n+3,n+4,n+5].map { |n| n + 1 }]


Array.map { |a| a.map! { |b| (b.is_a? Integer) ? 'X' : b } }