Pergunta

I have a two-dimensional array of a bunch of strings, including some empty strings. I want to replace the empty strings with nil. How do I do this in Ruby?

Sample array:

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

Desired output:

[['cat',nil,'dog',nil],[nil,nil,'fish',nil,'horse']]
Foi útil?

Solução

[['cat','','dog',''],['','','fish','','horse']].map do |arr|
  arr.map { |s| s unless s.empty? }
end
# => [["cat", nil, "dog", nil], [nil, nil, "fish", nil, "horse"]]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top