John Pollard
John Pollard

Reputation: 3899

Best practice to create a new array from another array in Ruby

Here is my code that works but I'm looking for a solution thats even cleaner. Im trying to avoid having to initalize my array first.

users = []
employees_to_import.each do |employee|
  users << User.new(employee.slice(:first_name, :last_name, :email))
end

Is there a method in ruby that I can call to do something like this?

users = employees_to_import.push_each do |employee|
  User.new(employee.slice(:first_name, :last_name, :email))
end

Not sure if a method like this exists, I didn't see anything in the docs but I figured I would ask.

Upvotes: 0

Views: 4936

Answers (1)

AmitA
AmitA

Reputation: 3245

You can use the map method:

users = employees_to_import.map do |employee|
  User.new(employee.slice(:first_name, :last_name, :email))
end

It is also aliased as collect.

From the documentation (here):

The map and collect basically return a new array with the results of running block once for every element:

(1..4).map { |i| i*i }      #=> [1, 4, 9, 16]

Upvotes: 4

Related Questions