2014-09-02 69 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