ruby hash
Hash organizes data in key-value pairs. Hash is so fast that it has an O(1) constant lookup time characteristic. Meaning, the time to look up for the value associated to a key is constant regardless of the collection’s size.Hash is created using curly braces.
Creating a Hash
detail = {} detail.class # Hash detail[:name] = "Alice" detail[:age] = 19 detail # => { :name=>"Alice", :age=>19 }
We can also initialize a hash when creating it. Again, the keys are each a symbol.
Creating and Initializing a Hash
detail = { name: "Alice", age: 19 } detail # => { :name=>"Alice", :age=>19 }
To get the value of a hash, we can use the [] (bracket) operator and then specify the key. If the value does not exist, nil is returned.
Retrieving a Value from a Hash by Using Its Key
detail[:name] # => "Alice" detail[:age] # => 19 detail[:number] # => nil
We can instantiate hash using the older notation (key => value) instead of the new one (key: value).
Defining a Symbol Using Older Notation
Initiating a hash in this way feels like something from the past. It’s normally preferred to use the new notation, especially if all the keys are symbols.
checkMe = { true => "Yes!", false => "No!", 1 => "Yes!", 0 => "No!", } [checkMe[false], checkMe[1]] # => ["No!", "Yes!"]
Using a Conditional Assignment Operator
detail # => { :name=>"Alice", :age=>19 } detail[:age] ||= 19 detail # => {:name=>"Alice", :age=>19} detail[:email] ||= "meAlice@example.com" detail # => { :name=>"Alice", :age=>19, :email=>"meAlice@example.com" }
To delete a mapping in a hash, we use the Hash#delete method. On top of that, invoking Hash#delete also returns the associated value.
Deleting a Key in a Hash
>> detail # => { :name=>"Alice", :age=>19, :email=>"meAlice@example.com" } >> detail.delete :email # => "meAlice@example.com" >> detail # => { :name=>"Alice", :age=>19 } >> detail.delete :nothing # => nil
To merge a hash with another one, we can use the Hash#merge method. This method returns a new hash instead of modifying in place.
Using Merge to Merge Two Hashes
detail # => { :name=>"Alice", :age=>19 } detail.merge(email: "meAlice@example.com") # => { :name=>"Alice", :age=>19, :email=>"meAlice@example.com" }
If we want to modify in place, we can use Hash #merge!
Converting a Hash to an Array, and Vice Versa
detail = [[:name, "Alice"], [:age, 19]].to_h # => { :name=>"Adam", :age=>27 } detail.to_a # => [[:name, "Alice"], [:age, 19]]
Just like an array, a hash is enumerable. As such, it has the each method to iterate its key-value pair