Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create hash within hash

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

like image 334
paul Avatar asked Jun 22 '11 15:06

paul


People also ask

How do you add hash to hash?

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.)

How do I create a new hash?

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.

How do I create a nested hash in Perl?

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.

How do you make hash hashes in Ruby?

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.


2 Answers

Joel's is what I would do, but could also do this:

test = Hash.new()
test['test1'] = Hash.new()
test['test1']['key'] = 'val'
like image 135
glortho Avatar answered Oct 06 '22 00:10

glortho


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
like image 27
Joel AZEMAR Avatar answered Oct 06 '22 00:10

Joel AZEMAR