2014-09-02 72 views
0

的數組我有符號的數組,我試圖讓一個從,或返回nil如果沒有找到獲取元素從符號

plugins = [:one, :two, :three] 
def resolve_plugin(name) 
    plugins[:"#{name}_plugin"] 
end 

當我打電話resolve_plugin(:one)我得到TypeError: no implicit conversion of Symbol into Integer。這樣做的正確方法是什麼?

+4

'plugins'是一個數組,而不是一個哈希,所以你只是想'plugins.include(叫什麼名字? .to_sym)? name.to_sym:nil'。如果'name'已經是一個符號,則放下'to_sym'。 – 2014-09-02 21:55:12

回答

0

Array地圖索引的對象,所以您可以通過索引來訪問它,而不是按值:

plugins = [:one, :two, :three] 

plugins[0] # => :one 
plugins[2] # => :three