Gareth Burrows
Gareth Burrows

Reputation: 1182

amalgamate two ruby arrays

Very simple one, but I need to run a bit of code for each admin user in a system plus 1 other user.

I can get the admin users like this.

account.users.where(:hr => 1).map(&:id)

and the individual user like this

user.manager_id

so how do I put these together to produce one unique array, as the user identified in the second piece of code "may" be found in the second. The code below seems to work, but I'm sure there's a more elegant way of doing it

myarray = []
a.employees.where(:hr => 1).each do |user|
  myarray << user.id
end

myarray << user.line_manager_id
myarray.uniq

This seems wrong as I am creating lots of objects just to get their IDs?

Upvotes: 0

Views: 51

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You can use the array "union" method Array#|:

account.users.where(:hr => 1).map(&:id) | [user.manager_id]

Upvotes: 3

usha
usha

Reputation: 29349

myarray = a.employees.where(:hr => 1).pluck(:id)
myarray << user.line_manager_id

myarray.uniq!

Documentation:

uniq!

pluck

Upvotes: 1

Related Questions