views:

230

answers:

4
I have a simple hash like so { "1234" => "5", "2345" => "6" }

How can I create a new hash with both the keys and values in side it? Like so:

{ key_id = "1234", value_id = "5" }, { key_id = "2345", value_id = "6" }
+6  A: 

What are you actually trying to achieve with this? If you're looking to iterate over all of the keys, you can use .keys:

h = { "1234" => "5", "2345" => "6" }
h.keys
=> ["1234", "2345"]

If you want to just create an array of hashes, you should be able to iterate over the keys:

h = { "1234" => "5", "2345" => "6" }
a = []

h.each {|k, v| a << {:key_id => k, :value_id => v}
Mr. Matt
A: 

You can loop through each pair of the original hash and build up an array of hashes:

hashes = []
{ "1234" => "5", "2345" => "6" }.each_pair {|key, value| hashes << { :key_id => key, :value_id => value } }

Will yield:

[{:key_id=>"2345", :value_id=>"6"}, {:key_id=>"1234", :value_id=>"5"}]
Michael Sepcot
A: 

What should the keys be for the derived hash, the same at the original? In that case use this snippet:

x = { "1234" => "5", "2345" => "6" }
y = {}

x.each do |key, value|
    y[key] = { "key_id" => key, "value_id" => value }
end
amarillion
A: 

By "merging" two hashes, I think you mean to put all the contents of two different hashes into one new hash. Because the keys of a hash must be unique, if the same key exists in the both source hashes, only one value can survive.

In this example, I merge the contents of hash x and hash y into hash z. The values in y will overwrite the values in z if there are any duplicate keys.

x = { "a" => "1","b" => "2","c" => "3" }
y = { "c" => "999","d" => "4","e" => "5" }
z = {}

x.each do |key,value|
  z[key] = value
end

y.each do |key,value|
  z[key] = value
end

The source hashes had a total of 6 keys. Because the key "c" was in both hases, the merged hash only has 5 keys.

=> {"a"=>"1", "b"=>"2", "c"=>"999", "d"=>"4", "e"=>"5"}
cgmack