Hash in ruby

Tram Ho

Hash is similar to arrays, and it different to each other by array is indexed with integers, and hash you can indexed it by string, expressions. formula, object ….. When you store a value in the hash you must provide 2 objects that are key (key) and value (value).
For example:

The powerfull of hash is that: they can use any object as an index. It has default value and will return nil when the key value does not exist in the hash.

Create a Hash

We have some different ways to generate a hash. Below you can see you can create an empty hash by:

And you also can create the new hash with the default as below:

If the key does not exist, the hash returns the default value

Another ways to create a hash in Ruby:

Add data into the hash

Delete data in hash

Other operations

Use eachthe loop of each attribute in the hash

Use each_key if only needed key by the hash

Use each_value if only needed value by the hash

Check key exists in hash

Check for empty hashes empty?

Hash length

Merge 2 hashes

has_key?(key)

The result will return true if the hash has a value equal to the key

include?(key)

The result will return true if the key exists in the hash

key(value)

Get the key key via value

keys

Returns an array containing the hash keys:

values

Returns an array containing hash values

**merge(other_hash) **

Returns a new hash including other_hash. If the key is duplicated then the value will be specified in other_hash

select {|key, value| block}

Returns a new hash containing matching pairs (block returns true)

Share the news now

Source : Viblo