morrime morrime - 4 months ago 11
Ruby Question

Ruby: How to loop hashes within an array?

I need to loop this so the user is prompted with "Name?" 3 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 3 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


I'm a beginner. Any suggestions would be greatly appreciated.

Answer
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