user3060126
user3060126

Reputation: 501

Replace Empty Cells in Array With Nil in Ruby?

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']]

Upvotes: 3

Views: 1592

Answers (1)

Kyle
Kyle

Reputation: 22278

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

Upvotes: 6

Related Questions