我有一堆字符串的二维数组,包括一些空字符串。我想用nil替换空字符串。我如何在Ruby中做到这一点?
示例数组:
[['cat','','dog',''],['','','fish','','horse']]
期望的输出:
[['cat',nil,'dog',nil],[nil,nil,'fish',nil,'horse']]
答案 0 :(得分:6)
[['cat','','dog',''],['','','fish','','horse']].map do |arr|
arr.map { |s| s unless s.empty? }
end
# => [["cat", nil, "dog", nil], [nil, nil, "fish", nil, "horse"]]