0

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
3
  • That's because name is set before you start initializing the array/hash. Why not do the same for number? Commented Aug 2, 2016 at 18:19
  • @JonnyHenly sorry I'm a bit new to this. What should I be setting number to? Commented Aug 2, 2016 at 18:21
  • number = rand(1000..9000) + 1 Commented Aug 2, 2016 at 18:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

10 Comments

Why did you change number.to_s[1..3] to number.to_s[-3, 3]?
Because he said the last three digits of the number.
Try [code dump] with no explanation, leads to comments like my previous comment.
@morrime I think you should open another question. but before try on your own and tell us where you find difficulties.
@morrime Sorry if I came off as sounding rude, that wasn't my intent. If you're having trouble learning Ruby, then you should check out Codecademy's Ruby Course, it's free, it's hands-on and does a pretty good job of conveying information.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.