Ido Traini
Ido Traini

Reputation: 83

Convert an array of hash with symbols

I have an array of hashes:

[{'object' => 'ob1', 'quantity' => '2'}, {'object' => 'ob2', 'quantity' => '3'}, .....]

I want to convert it to symbolized form:

[{:object => 'ob1', :quantity => '2'}, {:object => 'ob2', :quantity => '3'}, .....]

tried with:

symbolized_array = array.each => { |c| c.to_options }

but i didn't obtained any conversion, the symbolized_array is same as array

why?

Upvotes: 2

Views: 3089

Answers (4)

Stefan
Stefan

Reputation: 114138

i didn't obtained any conversion […] why?

to_options does return a new hash with the keys symbolized, but you didn't use that new hash – each merely traverses the array and at the end returns the array.

If you want to pick up the blocks results as the new array element, you have to use map:

array.map { |c| c.to_options }    # or array.map(&:to_options)

Alternatively there's to_options! (with a !) which would work along with each:

array.each { |c| c.to_options! }  # or array.each(&:to_options!)

That's because to_options! modifies the hashes in-place.


Note that to_options is an alias for symbolize_keys which might be a little clearer.

Upvotes: 3

Vasfed
Vasfed

Reputation: 18444

Since ruby 2.5 there's Hash#transform_keys:

array.map{|hash| hash.transform_keys(&:to_sym) }

Before that it was available in activesupport (part of rails) along with shortcut symbolize_keys

Upvotes: 8

kishore cheruku
kishore cheruku

Reputation: 521

Use below code. Then you will get expected output

array.map! {|my_hash| my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}}

Or simply you can use array.map(&:symbolize_keys). This code will be work on rails environment

Upvotes: 3

Ursus
Ursus

Reputation: 30056

You tagged rails so you can use symbolize_keys

array.map(&:symbolize_keys)

Upvotes: 7

Related Questions