A collection of hashing-value pairs, similar to this: "Employee" => "salary". It is similar to an array, except that the index is the type of any object that passes through any key, not an integer index.
Sequential traversal of a hashing or value may appear arbitrary, generally not in the insertion order. If the hash value of the key being accessed does not exist, the method returns nil.
To create a hash:
Using arrays, there are various ways to create hash values. You can create an empty hash of the new class method:
You can also use new to create a hash, which is a default value, otherwise it is simply nil:
Copy Code code as follows:
months = Hash.new ("month")
Or
months = hash.new "Month"
When accessing any of the hashing, there is a default value, and if the key or value does not exist, accessing the hash table will return the default value:
#!/usr/bin/ruby
months = hash.new ("month")
puts "#{months[0]}" puts
"#{months[72]}"
This will produce the following results:
Month
month
#!/usr/bin/ruby
H = hash["A" =>, "B" => "puts" #{h['
a ']} "
puts" #{h[' B ']} "
This will produce the following results:
You can use any Ruby object as a key or value, or even an array, so the following example is a valid
Hashing the built-in method:
We need to have a hash object instance call hashing method. As we have seen, the following is the way of the hash object to create an instance:
Hash[[key =>|, value]*] or
hash.new [or] hash.new (obj) [or]
hash.new {|hash, key| block}
This returns a new hash value with the given object fill. Now using the created object, we can call any available instance methods. For example:
#!/usr/bin/ruby
$, = ","
months = hash.new ("month")
months = {"1" => "January", "2" => "February"}
keys = Months.keys
puts "#{keys}"
This will produce the following results: