我希望根据条件更改结构键名称,例如,根据条件查看下面的哈希,构建名为结构的哈希而不是结构
test=
{
structure:
{
field1: 12
field2: 23
}
}
也许是这样的?
test=
{
cond ? structure: : structures:
{
field1: 12
field2: 23
}
}
答案 0 :(得分:1)
例如:
cond = true
cond = cond ? "structure" : "structures"
test = { "#{cond}".to_sym => { field1: 12, field2: 23 } }
#=> {:structure=>{:field1=>12, :field2=>23}}
cond = false
cond = cond ? "structure" : "structures"
test = { "#{cond}".to_sym => { field1: 12, field2: 23 } }
#=> {:structures=>{:field1=>12, :field2=>23}}
或
test = { "#{cond ? "structure" : "structures"}".to_sym => { field1: 12, field2: 23 } }
答案 1 :(得分:0)
您需要对您提出的建议进行一些小改动:
有关:
cond = true
我们获得:
test=
{
(cond ? :structure : :structures) =>
{
field1: 12,
field2: 23
}
}
#=> {:structure=>{:field1=>12, :field2=>23}}
有关:
cond = false
我们获得:
test=
{
(cond ? :structure : :structures) =>
{
field1: 12,
field2: 23
}
}
#=> {:structures=>{:field1=>12, :field2=>23}}