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
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
1 Comment
Ronan Lopes
give an upvote but I wanted a simple syntax, like my own answer I just posted... thanks!