0

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.

1
  • 1
    You could use Enumerable#each_with_object: employees_to_import.each_with_object([]) { |employee, users| users << User.new(employee.slice(:first_name, :last_name, :email)) }. Here map (as @AmitA has used) is preferable, but each_with_object is the method of choice in many other situations. Among other things (pertaining to scope), each_with_object avoids the need to first define the object (users = []) and then return it after the block (users). Commented Nov 18, 2015 at 4:53

1 Answer 1

4

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.