morrime morrime - 4 months ago 8
Ruby Question

Ruby: Undefined local variable or method

I'm trying to store a hash within an array with the keys "name", "number", and "email". I want the email to be a user's last name + last 3 digits of the number + "@btvs.com". I keep getting the error "undefined local variable or method" for number. How can I get this to output correctly? It has no problem grabbing the value from "name", but won't from "number".

data = Array.new()

puts "Name?, eg. Willow Rosenberg"
name = gets.chomp

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

puts data

Answer

Try

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[-3, 3] + "@btvs.com"
  }
]
puts data