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?
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?
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}
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}
{ |k| h[k[0]] = h.delete k }, as Hash#delete returns the value of the key being deleted.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.