How to use the keys from a Hash to make a new Hash where each key's value is the key itself?
So this is a trivial, but hopefully fun question. I need to make a Hash
with identical keys and values from the keys of an existing Hash
. Here's an example input along with my best attempt so far:
input = {'cat' => 'meow', 'dog' => nil}
Hash[*input.keys.map {|k| [k,k]}.flatten]
#=> {'cat' => 'cat', 'dog' => 'dog'}
I don't think this is particularly readable, so I was wondering if there was a better, more expressive syntax for doing this in Ruby, particularly one that might be more readable for future programmers who maintai开发者_开发技巧n the code?
This is how I would do the same thing in Python, and I find it to be slightly more readable:
dict([[a,a] for a in input])
But that could just be because I'm used to reading Python!
Looking for suggestions that will work with Ruby 1.8.6, which is the version I am constrained to.
h = {'cat' => 'meow', 'dog' => nil}
#=> {"cat"=>"meow", "dog"=>nil}
Hash[h.keys.map{|k| [k,k]}]
#=> {"cat"=>"cat", "dog"=>"dog"}
Here's another, a bit dirty way (and I think it works in 1.8.6):
h.merge(h){|k,v,v| k}
Hash[input.keys.zip(input.keys)] #=> {"cat"=>"cat", "dog"=>"dog"}
Or with inject:
input.keys.inject({}) { |h, k| h[k] = k ; h } #=> {"cat"=>"cat", "dog"=>"dog"}
The second also works in 1.8.6.
精彩评论