on-the-way
on-the-way

Reputation: 140

Minimize nested loops

I have the following code with nested loops. How can I minimize the loop?

users result is like:

users = [[35, 61, 62, 63, 64, 65, 66, 67, 68, 69, nil, 70, 71, 72, 73,
          74, 75, 78, 79, 92, 94, 95, 154, 164, 292, 293, 294, 295, 314],
         [],
         [35],
         [],
         [35, 79, 88],
         [],
         [],
         [36, 35, 56, 78, 87, 95, 65],
         [63, 72, 78, 80, 81, 82, 84, 87, 90, 93, nil, 96, 111, 157, 159, 160, 271,
          272, 66, 295, 296, 297, 298, 299, 300, 301, 305, 307, 308, 71, 315],
         [],
         [79, 83, 85, 86, 89, 91, 161, 162, 163, 67, 294, 302, 303, 304, 306,
          309, 310, 311, 312, 313],
         [],
         [314],
         [314],
         []
        ]

That's why I need to loop the object in each elements.

And array value is:

array = [309, 310, 305, 304, 90, 162, 78, 297, 296, 272, 271, 84, 91, 308,
         299, 79, 87, 298, 301, 163, 81, 72, 83, 111, 86, 313, 164, 300, 159,
         315, 160, 307, 82, 69, 312, 89
        ]

Thanks!

0.upto(users.count).each do |i|
  users[i].each do |user_id|
    if array.include?(user_id)
      puts user_id
    end
  end
end

Upvotes: 0

Views: 492

Answers (2)

lwassink
lwassink

Reputation: 1681

If each sub array of users has no repeated elements, then the following should work

users.each { |user| puts array & user }

Upvotes: 1

M. Karim
M. Karim

Reputation: 942

From my understanding, you want to get the common elements from users and array.

At first make the users array flatten to make it a single array. Then make it a uniq so that one id doesn't repeat again. compact will remove the nil values. After that make a & operation with array. And you got your result.

result = users.flatten.uniq.compact & array

Now if you want to print the result

puts result

Upvotes: 2

Related Questions