DEV Community

Discussion on: Eliminating Code Complexity by Finding Double Negatives

Collapse
 
codeandclay profile image
Oliver • Edited

I think you've moved in the right direction but the second implementation still makes my head hurt. How about something like this?

# Method call
items_found_for(volunteers)

# Method implementation
def items_found_for(volunteers)
  volunteers.reduce([]) do |items, volunteer|
    next items unless volunteer.items.any?
    items << volunteer.items
  end.flatten.uniq
end
Enter fullscreen mode Exit fullscreen mode

(Perhaps also with the flattening and removing of duplicates handled within the reduce block to avoid the intermediate arrays.)

Now there's no need to explicitly return the empty array because items_found_for will return an empty array if there's nothing to add to it.