How am I able to create a hash within a hash, with the nested hash having a key to indentify it. Also the elements that I create in the nested hash, how can I have keys for them as well
for example
test = Hash.new()
#create second hash with a name?? test = Hash.new("test1")??
test("test1")[1] = 1???
test("test1")[2] = 2???
#create second hash with a name/key test = Hash.new("test2")???
test("test2")[1] = 1??
test("test2")[2] = 2??
thank you
Merge two hashes On of the ways is merging the two hashes. In the new hash we will have all the key-value pairs of both of the original hashes. If the same key appears in both hashes, then the latter will overwrite the former, meaning that the value of the former will disappear. (See the key "Foo" in our example.)
Creating a Hash In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
format. Among all of the Perl's nested structures, a Multidimensional hash or Hash of Hashes is the most flexible. It's like building up a record that itself contains a group of other records. The format for creating a hash of hashes is similar to that for array of arrays.
Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.
Joel's is what I would do, but could also do this:
test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
my_hash = { :nested_hash => { :first_key => 'Hello' } }
puts my_hash[:nested_hash][:first_key]
$ Hello
or
my_hash = {}
my_hash.merge!(:nested_hash => {:first_key => 'Hello' })
puts my_hash[:nested_hash][:first_key]
$ Hello
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With