Ruby 哈希变量到数组(TypeError:无法将符号转换为整数)

Ruby 哈希变量到数组(TypeError:无法将符号转换为整数),ruby,arrays,Ruby,Arrays,这里是鲁比。我有这个数据库连接数组 @db_connection = [:host => "localhost", :port => 3306, :username => "user", :password => "password"] 但是当我像这样使用它的时候 connection(@db_connection) 返回我这个错误 TypeError: can't convert Symbol into Inte

这里是鲁比。我有这个数据库连接数组

@db_connection = [:host => "localhost", 
        :port => 3306, 
        :username => "user", 
        :password => "password"]
但是当我像这样使用它的时候

connection(@db_connection)
返回我这个错误

TypeError: can't convert Symbol into Integer
当数组静态放置在连接中时,它正在工作,但当将其作为变量放置时,它会给出一个错误

编辑: 我把它放在连接方法中,如下所示

connection(:host => "localhost", 
           :port => 3306, 
           :username => "user", 
           :password => "password")
并将其放置在一个变量中,如上面的示例所示。顺便说一句,我是ruby新手,这是一个哈希与数组的问题,答案如下。我为我的问题的混乱道歉:

用{}写你的散列。。。作为一个

或者使用新的Ruby>=1.9样式

这里的代码有问题

@db_connection = [:host => "localhost", 
                  :port => 3306, 
                  :username => "user", 
                  :password => "password"]
其计算结果为包装在数组中的哈希

[{:host=>"localhost", :port=>3306, :username=>"user", :password=>"password"}]
这是有效的Ruby代码,但一旦您的连接方法得到它,它可能很难使用它

编辑:用一个简单的例子,下面是我猜测正在发生的事情

def connection options
  puts "host is #{options[:host]}"
end

connection [host: "localhost"]

# TypeError: no implicit conversion of Symbol into Integer

这里发生的事情是您试图访问一个符号索引:数组上的主机。但是,由于数组的索引是数字索引的,因此数组试图将符号转换为整数,但无法实现。因此,类型错误。

如果您指的是散列文字,请使用{..}而不是[…],您能分享失败和成功的代码吗?顺便说一句,您展示了一个数组文字,它由一个包含四个键/值对的散列组成,而不是一个散列变量。这并不能解释为什么OP将该数组文字传递给连接而不是实例变量时会得到不同的结果。@PeterAlfvin,事实上是这样的。与哈希相比,数组具有完全不同的可用方法。如果他的连接函数将数组视为散列,他可能会遇到麻烦。我会留下更详细的解释作为编辑。@maček我想你误解了我的问题。OP表示,当阵列静态放置在连接中时,它可以工作。我将其解释为连接[:host=>localhost,:port=>3306,:username=>user,:password=>password]工作正常。这就是我不理解的。我把它解释为连接:host=>localhost。。。。没问题。干杯
[{:host=>"localhost", :port=>3306, :username=>"user", :password=>"password"}]
def connection options
  puts "host is #{options[:host]}"
end

connection [host: "localhost"]

# TypeError: no implicit conversion of Symbol into Integer