Dennis Ninj
Dennis Ninj

Reputation: 919

How to extract values and store in arrays from a hash map in ruby?

I already have an Hash map of school which has key as student's first name. I would like to extract all information and create hash map with student's School_ID as primary key. I am getting error

undefined local variable or method 'key1' for main:object

key1 = Array.new
array2 = Array.new

def print_info(school_hash)         
  school_hash.each do |student|     #school_hash  has key as first name
                                    #student[0] contains First Name student[1] all info
    key1.push(student[1].School_ID) #save school_id separately to use as a key
    array2.push(student[1])         # all infos including Address, Grade, School_ID, Sports
  end
  new_hash = Hash[key1.zip(array2)]
  printf("%s",new_hash)
end

Upvotes: 0

Views: 403

Answers (3)

DigitalRoss
DigitalRoss

Reputation: 146053

You could change key1 to @key1, and array2 to @array2.

Upvotes: 1

luacassus
luacassus

Reputation: 6710

When you define a new method in ruby a new scope will be created, see: metaprogramming access local variables for more details.

Instead of def print_info(school_hash) you could use lambda, for example

school_hash = lambda do |school_hash|
  # ..your method body
end

school_hash.call(hash)

Other solution - just put:

key1=Array.new
array2=Array.new

in the method's body.

Upvotes: 1

cydparser
cydparser

Reputation: 2087

Move key1 and array2 into the def block or pass them in as parameters. Ruby def blocks are not closures -- they cannot access local variables defined outside of them.

Upvotes: 2

Related Questions