我有我想要寫一個通用的檢查散列的數組,所以我想在一個鍵的名稱傳遞進行檢查。散列是用帶冒號前綴(符號)的鍵定義的。我無法弄清楚如何正確使用該變量作爲關鍵。即使密鑰存在於哈希中,使用該變量訪問它也會導致nil。如何通過變量訪問散列鍵?也許另外一個問題是,我如何將變量強制爲符號?如何通過變量訪問一個冒號哈希鍵紅寶石
在IRB我這樣做:
>> family = { 'husband' => "Homer", 'wife' => "Marge" }
=> {"husband"=>"Homer", "wife"=>"Marge"}
>> somevar = "husband"
=> "husband"
>> family[somevar]
=> "Homer"
>> another_family = { :husband => "Fred", :wife => "Wilma" }
=> {:husband=>"Fred", :wife=>"Wilma"}
>> another_family[somevar]
=> nil
>>
' 「丈夫」 .to_sym =>:husband'。 – 2014-08-27 22:33:50