How to convert an array to hash?

Asked

Viewed 223 times

0

I possess the following return:

[{"eh5g4vs84ah84gsdf4a8va"=>"information"}]

Is a hash within a array. I’d like to know how I take that Hash from within the array?

He’s the return of a consultation like this:

Promotions.no_tab_fields(organization.id, product.class).map do |custom_field|
  campo = { custom_field.hash_field => product.custom_columns[custom_field.hash_field] }
end

My question is to get inside the array.

I’ve tried to:

  • to_h
  • Hash(field) //field is the array that has the hash inside

2 answers

1


The return of a #map is an array. The structure you have is a hash array.

Just access with the index:

resultados = [{"eh5g4vs84ah84gsdf4a8va"=>"information"}]
resultados[0]
#=> {"eh5g4vs84ah84gsdf4a8va"=>"information"}

Or if you want to turn this array into a single hash, you can use Hash#merge. Just be careful that the keys of the different hashes do not conflict:

[{ a: 1 }, { b: 2 }, { c: 3 }].reduce(:merge)
#=> {:a=>1, :b=>2, :c=>3}

0

Alternatively:

[{"eh5g4vs84ah84gsdf4a8va"=>"information"}].first

hash_dentro_array, restante = *[{"eh5g4vs84ah84gsdf4a8va"=>"information"}]

Basically, you’re just taking the value at index 0 of the array, which is a hash. You would do the same if it were any type of value (integer, string, object, etc)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.