A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order.
Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil.
Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.
class MyClass attr_reader :str def initialize(str) @str = str end def eql?(o) o.is_a?(MyClass) && str == o.str end def hash @str.hash end end a = MyClass.new("some string") b = MyClass.new("some string") a.eql? b #=> true h = {} h[a] = 1 h[a] #=> 1 h[b] #=> 1 h[b] = 2 h[a] #=> 2 h[b] #=> 2
Convert an Array to a Hash
The <a href="/ruby/Hash/%5B%5D/class">Hash.[]</a> method converts an even number of parameters to a Hash. (The <a href="/ruby/Hash">Hash[]</a> method depends on the Hash class, but don’t confuse the method with the class itself). For example:
Hash['A', 'a', 'B', 'b'] # => {"A"=>"a", "B"=>"b"}
You can convert an array to a hash using the Hash[] method:
array = ['A', 'a', 'B', 'b', 'C', 'c'] hash = Hash[*array] # => {"A"=>"a", "B"=>"b", "C"=>"c"}
The * (splat) operator converts the array into an argument list, as expected by Hash[].
You can similarly convert an array of arrays to a Hash, by adding flatten:
array = [['A', 'a'], ['B', 'b'], ['C', 'c']] hash = Hash[*array.flatten] # => {"A"=>"a", "B"=>"b", "C"=>"c"}
This also comes in handy when you have a list of words that you want to convert to a Hash:
Hash[*%w( A a B b C c )] # => {"A"=>"a", "B"=>"b", "C"=>"c"}
Convert a Hash to an Array of Arrays using map
Although you‘ll always have to_a and it‘s faster, this trick is too cool to ignore…
Convert a Hash to an Array of Arrays using Enumerable#map

