Removing trailing empty values from an array in ruby
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 tra开发者_运维知识库iling empty and nil values alone. Please give me any suggestion on this..
This will do it and should be fine if you only have a couple trailing nil
s 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?"]
['a', "", nil].compact.reject(&:empty?) => ["a"]
精彩评论