Mega Man Mega Man - 3 months ago 11
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
map!
doesn't exist.

This, however, has no problems:

survey.map! { |feedback| %(_"#{feedback}_") }


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

Answer

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?)
survey.map! { |feedback| %(_"#{feedback}"_) }

Or you can chain-reassign:

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