Mega Man Mega Man - 1 year ago 89
Ruby Question

How to filter out empty elements in arrays

I have a line of code that iterates over an array and rejects any empty elements:

survey.reject!(&:empty?).map! { |feedback| %(_"#{feedback}"_) }

If the entire array is empty, this works as expected. If one of the elements in the array is not empty I get an error
doesn't exist.

This, however, has no problems:! { |feedback| %(_"#{feedback}_") }

function works when the entire array is empty, and
version works when the array isn't empty. How can I best consolidate these?

Answer Source

You've got to be careful when using in-place modifiers. As the documentation for reject! says:

Deletes every element of self for which the block evaluates to true, if no changes were made returns nil.

Due to that feature, you can't chain these like you can the versions that reliably make copies.

What you can do is do it on two lines:

survey.reject!(&:empty?)! { |feedback| %(_"#{feedback}"_) }

Or you can chain-reassign:

survey = survey.reject(&:empty?).map { |feedback| %(_"#{feedback}"_) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download