gpt4 book ai didi

ruby - 在 Ruby 中用 Nil 替换数组中的空单元格?

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

我有一堆字符串的二维数组,包括一些空字符串。我想用 nil 替换空字符串。我如何在 Ruby 中执行此操作?

示例数组:

[['cat','','dog',''],['','','fish','','horse']]

期望的输出:

[['cat',nil,'dog',nil],[nil,nil,'fish',nil,'horse']]

最佳答案

[['cat','','dog',''],['','','fish','','horse']].map do |arr|
arr.map { |s| s unless s.empty? }
end
# => [["cat", nil, "dog", nil], [nil, nil, "fish", nil, "horse"]]

关于ruby - 在 Ruby 中用 Nil 替换数组中的空单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233446/

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