How to convert a key value into int?

Viewed 58

I have a array of hash like:

data = [{a: 1, b: "2"}, {a: 4, b: 4}, {a: 6, b: "3"}]

Now I want that all value of related to key 'b' become int

And final output will be:

[{a: 1, b: 2}, {a: 4, b: 4}, {a: 6, b: 3}]
1 Answers

You can map your data array of hashes by merging the b key/value in every hash with its same value but converted to an integer:

data.map { |hash| hash.merge(b: hash[:b].to_i) }
# [{:a=>1, :b=>2}, {:a=>4, :b=>4}, {:a=>6, :b=>3}]
Related