简体   繁体   中英

How do I add two arrays together and collect ids where one or both can be null

I have a method where I add two arrays together and collect their IDs. The problem is, it's possible for one or both arrays to be null.

This is what I have:

all_items = old_duplicate_items.to_a + new_duplicate_items.to_a
all_items.map(&:id) unless all_items.blank?

Can this be improved upon?

If you're ok with an empty array as a result in the case of both input arrays being nil , then you could consolidate it as follows:

(old_duplicate_items.to_a + new_duplicate_items.to_a).map(&:id)

but that's about all I can see.

Your solution looks pretty good. Right now, it returns nil or a populated Array. If it's OK to return an empty array, you could try:

(old_duplicate_items.to_a + new_duplicate_items.to_a).map &:id

To preserve the nil return would require something at least as complex as what you have now:

(x = old_duplicate_items.to_a + new_duplicate_items.to_a).size > 0 ? x : nil

Or perhaps:

if (x = old_duplicate_items.to_a + new_duplicate_items.to_a).size > 0; x end
all_items = ((old_duplicate_items || []).to_a + (new_duplicate_items || []).to_a).map(&:id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM