Ashley Elder Ashley Elder - 9 months ago 52
Ruby Question

How to repeat single hash multiple times in one array?

I want to create dozens of logins that rely on data from this array, logins:

logins = [
{
email: Faker::Internet.email,
password: "password",
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name
},
{
email: Faker::Internet.email,
password: "password",
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name
}
]


What is a better way of writing this array rather than copy and pasting that hash dozens of times? I am familiar with x.times do but that wouldn't work on an array.

Here's the code where I pass in the logins:

logins.each do |login|
li = LoginInformation.new(login: login[:email], password: login[:password])
if UserManager.save(li)
company_ids.each do |id|
li.contacts.create(first_name: login[:first_name], last_name: login[:last_name], email_address: login[:email], company_id: id, is_employee: true)
end
end
end

Answer Source

One way to simplify the creation of your logins array is to pass the hash object with the included Faker methods as a block, like so:

logins = Array.new(10) { { email: Faker::Internet.email, password: 'password', first_name: Faker::Name.first_name, last_name: Faker::Name.last_name } }

You can replace the 10 in this example with the number of elements required for your use case.

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download