我正在互联网上搜索一些简单的解释,以解释红宝石中的哈希值,但我还没有发现(如果发现,请告诉我)。我正在寻找一种随时随地创建哈希值的好方法。这是我当前的示例:
home = {}
home['rooms'] = {}
home['rooms']['kitchen'] = 'this is kitchen'
home['rooms']['hall'] = 'welcome in hall'
但是这是很长的解释。我正在用红宝石搜索与此类似的东西:
home = {}
home['rooms']['kitchen'] = 'this is kitchen'
home['rooms']['kitchen']['some_parameter']['some_parameter2'] = 'random text'
我不想在每个步骤上定义哈希。
home['rooms'] = {}
home['rooms']['kitchen'] = {}
home['rooms']['kitchen']['some_parameter'] = {}
我希望我的意图很明确,否则我将在评论中回答。在我的代码中,我想定义新的哈希值。我以前不知道其结构,所以想法是当我创建新的var [p1] [p2] [p3]时,它将自动创建为哈希,并且不会产生错误。
实例化第一个哈希时,您可以传递整个哈希(如果您知道所需的键)。
类似这样的东西:
home = {
rooms: {
kitchen: '',
hall: ''
}
}
home[:rooms][:kitchen] = 'this is kitchen'
home[:rooms][:hall] = 'welcome in hall'
如果已经有了值:
home = {
rooms: {
kitchen: 'this is kitchen',
hall: 'welcome in hall'
}
}
如果您可以提供一个用例示例,则可能会得到更精确的答案。
编辑:如果要使用String
或Symbol
来访问密钥,请执行以下操作:
home = {
rooms: {
kitchen: 'this is kitchen',
hall: 'welcome in hall'
}
}.with_indifferent_access
实例化第一个哈希时,您可以传递整个哈希(如果您知道所需的键)。
类似这样的东西:
home = {
rooms: {
kitchen: '',
hall: ''
}
}
home[:rooms][:kitchen] = 'this is kitchen'
home[:rooms][:hall] = 'welcome in hall'
如果已经有了值:
home = {
rooms: {
kitchen: 'this is kitchen',
hall: 'welcome in hall'
}
}
如果您可以提供一个用例示例,则可能会得到更精确的答案。