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

时间:2012-04-11 02:03:59

标签: ruby string hash symbols

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

以下是摘录:

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

2 个答案:

答案 0 :(得分:3)

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

account_params[hkey.to_sym] = hvalue

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

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

答案 1 :(得分:0)

您可以使用此混音: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]
相关问题