1

How to remove the trailing empty and nil values from an array in Ruby.

The "Compact" function is not fullfil my requirement. It is removing all the 'nil' values from an array. But I want to remove the trailing empty and nil values alone. Please give me any suggestion on this..

1
  • What's causing you to have trailing empty and nil values in an array? Is it the result of splitting a string? Commented Dec 15, 2011 at 22:34

2 Answers 2

10

This will do it and should be fine if you only have a couple trailing nils and empty strings:

a.pop while a.last.to_s.empty?

For example:

>> a = ["where", "is", nil, "pancakes", nil, "house?", nil, '', nil, nil]
=> ["where", "is", nil, "pancakes", nil, "house?", nil, "", nil, nil]
>> a.pop while a.last.to_s.empty?
=> nil
>> a
=> ["where", "is", nil, "pancakes", nil, "house?"]

The .to_s.empty? bit is just a quick'n'dirty way to cast nil to an empty string so that both nil and '' can be handled with a single condition.

Another approach is to scan the array backwards for the first thing you don't want to cut off:

n = a.length.downto(0).find { |i| !a[i].nil? && !a[i].empty? }
a.slice!(n + 1, a.length - n - 1) if(n && n != a.length - 1)

For example:

>> a = ["where", "is", nil, "pancakes", nil, "house?", nil, '', nil, nil]
=> ["where", "is", nil, "pancakes", nil, "house?", nil, "", nil, nil]
>> n = a.length.downto(0).find { |i| !a[i].nil? && !a[i].empty? }
=> 5
>> a.slice!(n + 1, a.length - n - 1) if(n && n != a.length - 1)
=> [nil, "", nil, nil]
>> a
=> ["where", "is", nil, "pancakes", nil, "house?"]
Sign up to request clarification or add additional context in comments.

Comments

2
['a', "", nil].compact.reject(&:empty?) => ["a"]

2 Comments

Downvote. You are not removing tailing empty and nil values this way
Correct, I wonder how I could miss that part of the question.

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.