开发者

Removing all items from an array of arrays which are empty of blank

I have an array of arrays and I would like to remove all the items that have elements which are nil or empty after stripping spaces. Look at this snippet:

x = Array.new
x << ["A","B", " ", "D"]
x << ["","  ", nil, ""]
x << ["E","Q", "F", "M"]

I would like to remove the second record 开发者_运维技巧because, it contains no real data.

What would be the best way to do this? Should I simply iterate over the array and and write if-else conditions to test?


If using plain Ruby, you can do

x.reject{ |arr| arr.all? {|elem| elem.nil? || elem.strip.empty? }}

If using rails, thanks to the helper methods you can do

x.reject{ |arr| arr.all?(&:blank?) }

The key methods are reject and blank?


x.reject { |a| a.join.strip.length == 0 }


If first array will contain nil, when Chubas variant don't work. Lets slightly modify it:

(using rails)

x.compact.reject{ |arr| arr.all?(&:blank?) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜