我有以下代码。我不明白为什么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'
一起使用?
答案 0 :(得分:2)
问题是JSON中的{"user":"postgres"}
表示:
{"user" => "postgres"}
在Ruby中,而在Ruby中则意味着:
{:user => "postgres"}
由于您将其作为JSON,因此您需要访问以下值:
auth["user"]
而不是:
auth[:user]
这是nil
,因为哈希缺少密钥:user
。
答案 1 :(得分:1)
因为'key'
是String
而:key
是Symbol
- 这些是Ruby中的两个不同的东西。
可能有些令人困惑,因为:'key'
或'key':
也是Symbol
要使其正常工作,只需使用{{1}访问Hash
字段,像:
Symbol
要将String indexed Hash转换为Symbol indexed 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';