tbrooke
tbrooke

Reputation: 2197

Change Hash Array keys to strings

I have this Hash:

{["word"]=>1, ["cat"]=>2, ["tree"]=>1, ["dog"]=>1}

But I want to have this Hash:

{"word"=>1, "cat"=>2, "tree"=>1, "dog"=>1}

I have made several attempts with each_key and join but nothing seems to work.

How do I do it?

Upvotes: 0

Views: 72

Answers (3)

Jeff Price
Jeff Price

Reputation: 3229

This does the trick.

h = {["word"]=>1, ["cat"]=>2, ["tree"]=>1, ["dog"]=>1}
h.keys.each { |k| h[k.first] = h.delete(k) }

h is now {"word"=>1, "cat"=>2, "tree"=>1, "dog"=>1}

Upvotes: 1

Stefan
Stefan

Reputation: 114188

Another one:

hash = {["word"]=>1, ["cat"]=>2, ["tree"]=>1, ["dog"]=>1}

hash.map { |(k), v| [k, v] }.to_h
#=> {"word"=>1, "cat"=>2, "tree"=>1, "dog"=>1}

Upvotes: 5

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

These kinds of situations arises so often with Ruby hashes, that I wrote methods to solve them in my y_support gem. First, type in the command line gem install y_support, and then:

require 'y_support/core_ext/hash'

h = { ["word"]=>1, ["cat"]=>2, ["tree"]=>1, ["dog"]=>1 }
h.with_keys &:first
#=> {"word"=>1, "cat"=>2, "tree"=>1, "dog"=>1}

Another way of writing the same would be

h.with_keys do |key| key[0] end

Other useful methods defined in y_support gem are Hash#with_values, Hash#with_keys!, Hash#with_values! (in-place modification versions), and Hash#modify, which "maps a hash to a hash" in the same way as Array#map maps an array to an array.

Upvotes: 0

Related Questions