morrime
morrime

Reputation: 493

How to loop hashes within an array

I need to use a loop in my code so the user is prompted with "Name?" three times, and each answer is stored as a new hash within the data array. Each answer should also have a new random number generated for it, and an email.

I need puts data to output all three hashes and their contents. I've tried using 3.times do, but I'm having trouble:

data = Array.new()

puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
    data = [
        {
        name: name,
        number: number,
        email: name.split(' ').last + number.to_s[1..3] + "@btvs.com"
        }
    ]

puts data

Upvotes: 0

Views: 36

Answers (1)

chumakoff
chumakoff

Reputation: 7024

data = []

3.times do
  puts "Name?, eg. Willow Rosenberg"
  name = gets.chomp
  number = rand(1000..9000) + 1

  hash = {
    name: name,
    number: number,
    email: name.split(' ').last + number.to_s[1..3] + "@btvs.com"
  }

  data << hash
end

puts data

Upvotes: 1

Related Questions