[英]Ruby: Adding an Empty Array to a Dictionary
I am trying to create an array within a dictionary as follows. 我正在尝试在字典中创建数组,如下所示。
What I would like to have: 我想要的是:
"Message": {
[
"0": "This is a message"
]
}
What I have now: 我现在所拥有的:
"Message": {
"0": ["This is a message"
]
}
I am using the following code to initialize the Message dictionary, and the array within it. 我正在使用以下代码初始化消息字典以及其中的数组。
if not_found
convoNum = 0
arrayIndex = 0
sessions["total"] = (sessions["total"].to_i + 1).to_s
sessions["users"]["#{sessions["total"]}"] = {"arrayIndex"=>"#{arrayIndex}", "convoNum"=>"0"}
sessions["users"]["#{sessions["total"]}"]["Message"] = {}
sessions["users"]["#{sessions["total"]}"]["Message"][sessions["users"]["#{sessions["total"]}"]["Message"].length] = []
end
I am having trouble in rendering my desired layout. 我在渲染所需的布局时遇到麻烦。 Simply adding sessions["users"]["#{sessions["total"]}"]["Message"] = {[]}
causes my database to crash upon initiation. 只需添加sessions["users"]["#{sessions["total"]}"]["Message"] = {[]}
导致数据库在启动时崩溃。 Any help in getting to the first layout would be appreciated. 任何帮助获得第一个布局将不胜感激。
When you say this: 当你这样说:
{
[
"0": "This is a message"
]
}
That is not valid Ruby. 那是无效的Ruby。 You're putting a key/value pair in an array, that doesn't make any sense. 您正在将键/值对放入数组中,这没有任何意义。
You cannot have (Array cannot have key value pairs) 您不能拥有(数组不能有键值对)
"Message": {
[
"0": "This is a message"
]
}
You can have 你可以有
"Message": {
"0": "This is a message",
"1": "Next message"
}
You can initialize it like this 你可以这样初始化
sessions["users"]["#{sessions["total"]}"]["Message"] = {}
And add values like 并添加像
sessions["users"]["#{sessions["total"]}"]["Message"]["0"] = "This is a message"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.