3

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

1 Answer 1

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"]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.