为什么我的代码在使用哈希符号而不是哈希字符串时会中断?

我有一个场景,当我尝试使用符号访问哈希键时,它不起作用,但当我用字符串访问它时它工作正常。 我的理解是建议使用符号而不是字符串,所以我试图清理我的脚本。 我在我的脚本中的其他地方使用哈希符号,只是这个特定的场景不起作用。

这是片段:

account_params ={} File.open('file', 'r') do |f| f.each_line do |line| hkey, hvalue = line.chomp.split("=") account_params[hkey] = hvalue end end account_scope = account_params["scope"] 

这是有效的,但如果我使用它不符号,如下所示:

 account_scope = account_params[:scope] 

当我使用符号时,我得到:

 can't convert nil into String (TypeError) 

我不确定它是否重要,但这个特定哈希值的内容看起来像这样:

 12345/ABCD123/12345 

您从文件中读取的密钥是一个字符串。 实际上,您从文件中读取的所有内容都是字符串。 如果您希望哈希中的键是符号,则可以更新脚本来执行此操作:

 account_params[hkey.to_sym] = hvalue 

这会将“hkey”变成符号而不是使用字符串值。

Ruby提供了各种类型的方法,这些方法将值强制转换为不同的类型。 例如:to_i将它带到一个整数,to_f到一个浮点数,而to_s将把某些东西带回一个字符串值。

你可以使用这个混音: https : //gist.github.com/3778285

这将向现有的单个Hash实例添加“Hash With Indifferent Access”行为,而不复制或复制该哈希实例。 在您从File中读取时,或者从Redis读取参数哈希时,这可能非常有用。

有关详细信息,请参阅Gist中的注释。

 require 'hash_extensions' # Source: https://gist.github.com/3778285 account_params = {'name' => 'Tom' } # a regular Hash class << account_params include Hash::Extensions::IndifferentAccess # mixing-in Indifferent Access on the fly end account_params[:name] => 'Tom' account_params.create_symbols_only # (optional) new keys will be created as symbols account_params['age'] = 22 => 22 account_params.keys => ['name',:age]