Question

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']]
Was it helpful?

Solution

[['cat','','dog',''],['','','fish','','horse']].map do |arr|
  arr.map { |s| s unless s.empty? }
end
# => [["cat", nil, "dog", nil], [nil, nil, "fish", nil, "horse"]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top