user3602045 user3602045 - 2 months ago 7
Ruby Question

How do I call a variable to a method in Ruby (NOT Rails)

people = {}

def add

puts "Enter the name of the person you would like to add in the database."
name = gets.chomp.to_s

if people[name].nil?

puts "What is #{name}'s age?"
age = gets.chomp.to_i

people[name] = age.to_i
end

puts "Would you like to add?"
choice = gets.chomp

if choice == "yes"
add
end

end


So Ive got people outside my method "add", I get an error "undefined local variable or method `people' for main: Object (NameError)"

I am getting an error ass soon as people[name].nil? line comes.

I have to create a database, I have more methods like update and delete, how do I use / call "people" inside these methods?

kfb kfb
Answer

Global variables should be prefixed by $ in Ruby, so you need $people in place of people. Alternatively, you can pass in people to your add function.