为什么我的代码在使用散列符号而不是散列字符串时中断? [英] Why does my code break when using a hash symbol, instead of a hash string?
问题描述
我有一个场景,当我尝试使用符号访问哈希键时,它不起作用,但是当我用字符串访问它时,它工作正常。这是我的理解,符号建议在字符串,所以我想清理我的脚本。我在脚本的其他地方使用了散列符号,这只是这种特定的场景不起作用。
以下是代码片段:
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 [ 范围]
这可以起作用,但是如果我使用它不符合的符号,如下所示:
account_scope = account_params [:范围]
当我使用一个符号时:
不能将nil转换为String (TypeError)
我不确定它是否重要,但是此特定哈希值的内容看起来像像这样:
12345 / ABCD123 / 12345
您从文件中读取的关键字是字符串。实际上,您从文件中读取的所有内容都是一个字符串。如果你希望hash中的键是符号,你可以更新脚本来做这件事:
account_params [hkey。 to_sym] = hvalue
这会将hkey转换为符号,而不是使用字符串值。 / p>
Ruby提供了多种这些类型的方法,它们会将值强制为不同的类型。例如:to_i会将其转换为整数,to_f转换为浮点数,to_s将返回字符串值。
I have a scenario that when I try to access a hash key using a symbol it doesn't work, but when I access it with a string it works fine. It is my understanding that symbols are recommended over strings, so I am trying to clean my script. I am using hash symbols elsewhere in my script, it is just this specific scenario that does not work.
Here is the snippet:
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"]
This works, however if I use a symbol it doesn't, as shown below:
account_scope = account_params[:scope]
When I use a symbol I get:
can't convert nil into String (TypeError)
I am not sure if it matters, but the contents of this specific hash value looks something like this:
12345/ABCD123/12345
The key you're reading in from the file is a string. In fact, everything you're reading in from the file is a string. If you want the keys in your hash to be symbols, you could update the script the do this instead:
account_params[hkey.to_sym] = hvalue
This will turn "hkey" into a symbol instead of using the string value.
Ruby provides a variety of these types of methods which will coerce the value into a different type. For instance: to_i will take it to an integer, to_f to a float, and to_s will take something back to a string value.
这篇关于为什么我的代码在使用散列符号而不是散列字符串时中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!