Why does my code break when using a hash symbol, i

2019-07-23 11:55发布

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

2条回答
做自己的国王
2楼-- · 2019-07-23 12:15

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-23 12:32

you can use this Mix-In: https://gist.github.com/3778285

This will add "Hash With Indifferent Access" behavior to an existing single Hash instance, without copying or duplicating that hash instance. This can be useful in your case, when reading from File, or also when reading a parameter hash from Redis.

See comments inside Gist for more details.

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]
查看更多
登录 后发表回答