rubyist
rubyist

Reputation: 3132

reject nil values while appending to ruby array inside loop

I have a loop inside which I am appending the result of the loop to an array. The code is like this

urls = []
series_id = [100,200,300,400]
series_id.each do |id|
  result_urls += iterate_id_and_get_urls(id)
end

def iterate_id_and_get_urls(id)
  #do something with id and maps it and returns its url which would result in an array
  #return that url array
end

But iterate_id_and_get_urls(id) can also return nil sometimes which would result nil to be appended in result_urls. How can I avoid that. I am looking for something like the below

result_urls += iterate_id_and_get_urls(id) unless nil?

Upvotes: 1

Views: 380

Answers (3)

Kranthi
Kranthi

Reputation: 1417

You can try something like

series_id.each do |id|
  if value = iterate_id_and_get_urls(id)
    result_urls += value.compact
  end
end

So nil url's will not get added to result_urls

Compact : Returns a copy of self with all nil elements removed.

Upvotes: 2

Uri Agassi
Uri Agassi

Reputation: 37409

How about using flat_map:

result_urls = series_id.flat_map { |id| iterate_id_and_get_urls(id) }.compact

or even:

result_urls = series_id.flat_map { |id| iterate_id_and_get_urls(id) || [] }

Upvotes: 3

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

series_id.map( &method( :iterate_id_and_get_urls ) ).compact.reduce( [], :+ ).compact

Upvotes: 1

Related Questions