Create a hash with default value : Hash Creation « Hash « Ruby






Create a hash with default value

h = Hash.new("Go Fish")
h["a"] = 100
h["b"] = 200
h["a"]  100
h["c"]  
# The following alters the single default object
h["c"].upcase!  
h["d"]  
h.keys   

 








Related examples in the same category

1.A hash ( associative array or a dictionary) is an array holding a collection of data,
2.Hashes use braces instead of brackets to let the Ruby interpreter know what is being created.
3.Hash has a class method [], which is called in either one of two ways: with a comma separating the pairs
4.Instead of integers, you could use strings for the keys
5.The hash definition is enclosed in curly braces, whereas an array is defined in square brackets.
6.Element Assignment
7.you can store numbers in hashes
8.Using Hashes
9.Creating a Hash with a Default Value
10.creates a new default object each time