0

I wanna do something like this: Let's say I have a array of users names ["John", "Mary"], etc... and I wanna create a array with new User records, where name attribute is initialized by those values. What is the easiest way to do that?

2 Answers 2

1

Pass your array into this method:

def create_users(names):
  users = []
  names.each do |name|
    u = User.create(:name => name)
    users << u
  end
  users
end

This:

  • takes an array of names in
  • creates an empty array to hold the created users
  • creates a user for each name and adds the user to the array
  • returns the array
Sign up to request clarification or add additional context in comments.

1 Comment

give an upvote but I wanted a simple syntax, like my own answer I just posted... thanks!
1

Found the answer by myself:

["john", "mary"].map{|u| User.new(name: u)}

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.