2012-04-19 69 views
0

我已經有一個學校的哈希圖,它具有作爲學生的名字的關鍵。我想提取所有信息並創建散列圖,並將學生的School_ID作爲主鍵。 我收到錯誤如何從紅寶石散列圖中提取值並存儲在數組中?

未定義局部變量或者用於主要方法「KEY1」:對象

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 

回答

2

移動KEY1和ARRAY2到DEF塊或將它們作爲參數。 Ruby def塊不是閉包 - 它們不能訪問在它們之外定義的局部變量。

1

當您在ruby中定義一個新的方法時,將會創建一個新的作用域,更多詳細信息請參見:metaprogramming access local variables。在方法體

key1=Array.new 
array2=Array.new 

:只是把 -

而不是def print_info(school_hash)你可以使用拉姆達,例如

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

school_hash.call(hash) 

其他的解決方案。

1

您可以將key1更改爲@key1array2@array2