简体   繁体   English

从Ruby删除数组中的尾随空值

[英]Removing trailing empty values from an array in ruby

How to remove the trailing empty and nil values from an array in Ruby. 如何从Ruby中的数组中删除尾随的empty和nil值。

The "Compact" function is not fullfil my requirement. “紧凑”功能无法满足我的要求。 It is removing all the 'nil' values from an array. 它正在从数组中删除所有“ nil”值。 But I want to remove the trailing empty and nil values alone. 但是我只想删除尾随的empty和nil值。 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: 如果您只有一对尾随nil和空字符串,则可以做到这一点,应该没问题:

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? .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. 位只是将nil强制转换为空字符串的一种快捷方式,因此nil''都可以用一个条件处理。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM