Xeen
Xeen

Reputation: 7003

How to create email address generator with Ruby?

  def emails
    i = 0
    number = rand(252...4350)

    males = ["tom", "jack", "adam"]
    females = ["elizabeth", "rose", "juliet"]

    surnameMales = ["oak", "yew", "timber"]
    surnameFemales = ["rosewelth", "gates", "jobs"]

    providers = ["gmail.com", "hotmail.com", "yahoo.com"]

    while i <= 100 do
      @addresses << 
    end
  end

What I want to do is pick a random number, name, surname and provider and put them all together + attach a random number at the end of the surname so that it looks, for example, like this: [email protected], but kind of got stuck at the point where I have to put the whole thing together. As you can probably tell, I want to create a 100 random emails for testing purposes.

Can you please point me out how I could do what I have intended to do with Ruby?

Upvotes: 2

Views: 5288

Answers (3)

Henrik Andersson
Henrik Andersson

Reputation: 47172

Use a combination of string interpolation and Array#sample.

"#{females.sample}.#{surnameFemales.sample}#{rand(252...4350)}@#{providers.sample}"
>> "[email protected]"

Upvotes: 3

Nick Veys
Nick Veys

Reputation: 23939

Is your goal to do this as an exercise or is this just something you're trying to get done? If it's the latter, install the faker gem and just use it:

Faker::Internet.email #=> "[email protected]"

For 100:

100.times.map { Faker::Internet.email }

Upvotes: 11

FeifanZ
FeifanZ

Reputation: 16316

There's a couple ways to join strings in Ruby. Inline placeholders seems to make the most sense here:

@addressess << "#{ males.sample }.#{ surnameMales.sample }#{ number }@#{ providers.sample }"

In a double-quoted string, #{ expr } is evaluated and subbed inline. "#{ 1 + 1 }" outputs "2", for example.

Also a couple ways you can distinguish male or female — for example, checking if a random number is even or odd:

name = if rand(1..100) % 2 == 0 ? "#{ males.sample }.#{ surnameMales.sample }" : "#{ females.sample }.#{ surnameFemales.sample }"
@addresses << "#{ name }#{ number }@#{ providers.sample }"

Upvotes: 1

Related Questions