简体   繁体   中英

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

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.

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.

您可以将key1更改为@key1 ,将array2更改为@array2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM