user3602045 user3602045 - 1 year ago 62
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

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

if choice == "yes"


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download