Richlewis
Richlewis

Reputation: 15384

Unique item from array when seeding data in Rails

I was wondering how I could select a random item from an array each time I create a record when seeding.

I know to select a random item, I can use

array_one = ["one", "two", "three"]
array_one.sample
one

Or if I want to select each value one time only (sample takes an argument)

array_one = ["one", "two", "three"]
array_one.sample(3)
["two", "one", "three"]

But how would I do it in the following circumstance

email_address_array = ['[email protected]', '[email protected]', '[email protected]']

3.times {
  user = User.create({
    email: email_address_array.sample ## not sure how to set this up  
  })
}

Upvotes: 1

Views: 661

Answers (3)

rogal111
rogal111

Reputation: 5933

Pop elements from shuffled array:

email_address_array = ['[email protected]', '[email protected]', '[email protected]']
shuffled_email_address_array = email_address_array.shuffle

3.times {
  user = User.create({
    email: shuffled_email_address_array.pop
  })
}

Upvotes: 4

jerhinesmith
jerhinesmith

Reputation: 15500

Not sure why you need to do the shuffle inside of the loop...

%w([email protected] [email protected] [email protected]).shuffle.each do |random_email|
  User.create(email: random_email)
end

Upvotes: 0

ptd
ptd

Reputation: 3053

Assuming your array has no duplicate values, you can do:

User.create(email: email_address_array.delete(email_address_array.sample))

This will return a random entry from the array while also deleting it from that array. This also assumes you don't need the array again later in your seeds file.

Upvotes: 1

Related Questions