0

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

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.