0

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?

4
  • Construct a new hash with correct keys. Commented Sep 4, 2014 at 14:13
  • This sounds like an XY problem. Maybe you should figure out why your keys are being created as arrays? Odds are good you're doing something wrong when the hash is created, and now you're trying to clean up. Commented Sep 4, 2014 at 19:22
  • I am getting duplicates from a string:phrase = "the dog and the dog" Commented Sep 5, 2014 at 1:33
  • phrase = "The dog and the dog" h = Hash.new(0) phrase.each { |e| h[e] += 1 } return h Commented Sep 5, 2014 at 1:33

3 Answers 3

5

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}
Sign up to request clarification or add additional context in comments.

1 Comment

@BroiSatse that's Ruby's array decomposition feature
1

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}

1 Comment

Nice one, +1, but note that in the block, you can write directly { |k| h[k[0]] = h.delete k }, as Hash#delete returns the value of the key being deleted.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.