Find an Online Tutor Now

Asked • 06/12/19

Map and Remove nil values in Ruby?

I have a map which either changes a value or sets it to nil. I then want to remove the nil entries from the list. The list doesn't need to be kept.This is what I currently have:<!-- language: lang-rb --> items.map! { |x| process_x url } # [1, 2, 3, 4, 5] => [1, nil, 3, nil, nil] items.select! { |x| !x.nil? } # [1, nil, 3, nil, nil] => [1, 3]I'm aware I could just do a loop and conditionally collect in another array like this:<!-- language: lang-rb --> new_items = [] items.each do |x| x = process_x x new_items.append(x) unless x.nil? end items = new_itemsBut it doesn't seem that Ruby-esque. Is there a nice way to run a function over a list removing/excluding the nils as you go?

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.