Ruby 从符号数组中获取元素

Ruby 从符号数组中获取元素,ruby,Ruby,我有一个符号数组,我正试图从中获取一个,如果没有找到,则返回nil plugins = [:one, :two, :three] def resolve_plugin(name) plugins[:"#{name}_plugin"] end 当我调用resolve\u plugin(:one)时,我得到了TypeError:没有将符号隐式转换为整数。正确的方法是什么?一个数组将索引映射到对象,因此您可以通过索引而不是值来访问它: plugins = [:one, :two, :three]

我有一个符号数组,我正试图从中获取一个,如果没有找到,则返回nil

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

当我调用
resolve\u plugin(:one)
时,我得到了
TypeError:没有将符号隐式转换为整数
。正确的方法是什么?

一个
数组将索引映射到对象,因此您可以通过索引而不是值来访问它:

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

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

plugins
是一个数组,不是散列,所以您只需要
plugins.include?(name.to_sym)?name.to_sym:nil
。如果
name
已经是一个符号,请将
放到\u sym
中。