通过符号而不是字符串来哈希密钥访问

时间:2015-08-28 13:47:55

标签: ruby

我有以下代码。我不明白为什么table['something']table[:something]不同。

require 'json'
data = '[{"type":"local","db":"all","user":"postgres","addr":null,"method":"ident"},{"type":"local","db":"all","user":"all","addr":null,"method":"ident"},{"type":"host","db":"all","user":"all","addr":"0.0.0.0/0","method":"md5"},{"type":"host","db":"all","user":"all","addr":"::1/128","method":"md5"},{"type":"local","db":"communicator","user":"communicator","addr":" ","method":"trust"}]'
table = JSON.parse(data)
table.each do | auth |
  if (auth['user'])
    print( '\n\n\n' + auth[:user] )
  end
end

print( '\n\n\n' + auth[:user] )一致,我收到错误:

TypeError: no implicit conversion of nil into String
        from (irb):88:in `+'

这意味着通过table访问:key'key'不同。 为什么?如何转换table以使其与:key而不是'key'一起使用?

3 个答案:

答案 0 :(得分:2)

问题是JSON中的{"user":"postgres"}表示:

{"user" => "postgres"}

在Ruby中,而在Ruby中则意味着:

{:user => "postgres"}

由于您将其作为JSON,因此您需要访问以下值:

auth["user"]

而不是:

auth[:user]

这是nil,因为哈希缺少密钥:user

答案 1 :(得分:1)

因为'key'String:keySymbol - 这些是Ruby中的两个不同的东西。

可能有些令人困惑,因为:'key''key':也是Symbol要使其正常工作,只需使用{{1}访问Hash字段,像:

Symbol

要将String indexed Hash转换为Symbol indexed Hash,请参阅以下问题:

Best way to convert strings to symbols in hash

答案 2 :(得分:1)

符号:键不是字符串'键',就像数字3不是字符串'3'。要将String转换为键,可以使用key.to_sym

关于两个其他SO问题之间的差异已经被问到。 What's the difference between a string and a symbol in Ruby? 另请参阅this文章

EDIT 如果您无法控制源

,则可以将键更改为符号
select distinct b.*
from ((select book_id, clean_page_content as page_content, 'clean' as status, reg_date
       from book_db_clean_pages t
      ) union all
      (select book_id, dirty_page_content as page_content, 'dirty' as status, reg_date
       from book_db_dirty_pages e
      )
     ) b
where book_id = 'sarafi_book_5' and reg_date = '2015-08-26';