Pippo
Pippo

Reputation: 925

how can I build a key name of a hash based on a condition

I am looking to change the structure key name based on a condition, for example, looking at the hash below, based on a condition, build the hash named structures rather than structure

test= 
{
  structure:
  {
    field1: 12
    field2: 23
  }
}

Maybe something like this?

test= 
{
  cond ? structure: : structures:
  {
    field1: 12
    field2: 23
  }
}

Upvotes: 1

Views: 51

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110665

You need to make just a couple of small changes to what you proposed:

For:

cond = true

we obtain:

test= 
{
  (cond ? :structure : :structures) =>
  {
    field1: 12,
    field2: 23
  }
}
  #=> {:structure=>{:field1=>12, :field2=>23}} 

For:

cond = false

we obtain:

test= 
{
  (cond ? :structure : :structures) =>
  {
    field1: 12,
    field2: 23
  }
}
  #=> {:structures=>{:field1=>12, :field2=>23}} 

Upvotes: 0

pangpang
pangpang

Reputation: 8821

For example:

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}}

or

test = { "#{cond ? "structure" : "structures"}".to_sym  => { field1: 12, field2: 23 } }

Upvotes: 1

Related Questions