Ruby - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Ruby Hashes

Ruby Hash

shape Introduction

This chapter demonstrates about the Ruby Hash which is data structure used to store the items by associated keys and following are the concepts covered in this chapter.
  • About Hash
  • Hash Methods

About Hash

shape Description

A hash is an data structure which stores items by asociated keys which is differentiated against arrays and which store items by an indexed order. Entries in a hash are regularly alluded to as key-values pairs which makes a associative representation of data. Most normally, a hash is made utilizing symbols as keys and any data types as values. All key-value pairs in a hash are encompassed by curly braces {} and <span style="color: #ff6600;"comma seperated. Hashes can be made with two syntax's in which old syntax comes with => sign to isolate the key and the value. The code below demonstrates the older syntax of Hash as shown below. [ruby] old_syntax_hash = {:name => 'bob'} => {:name=>'bob'} [/ruby] In Ruby 1.9 a new syntax introduced which is simpler then older syntax but it produce the same result. The code below demonstrates the Hash new syntax as shown below. [ruby] new_hash = {name: 'bob'} => {:name=>'bob'} [/ruby] The code below demonstrates to creating the hashes as shown below. [ruby] months = Hash.new( "month" ) puts "#{months[0]}" puts "#{months[72]}" [/ruby] Result By running the above code in command prompt, the output can be obtained as shown in the image below. If Ruby have multiple elements when user want to iterate over a hash with each element which is similar to iterating over arrays with some differences in which user need to use the each method. The code below demonstrates to iterating over hashes as shown below. [ruby] person = {name: 'bob', height: '6 ft', weight: '160 lbs', hair: 'brown'} person.each do |key, value| puts "Bob's #{key} is #{value}" end [/ruby] Result By running the above code in command prompt, the output can be obtained as shown in the image below.

Hash Methods

shape Description

Ruby have the several hash methods in which user need to have Hash object instance to call an Hash method the code below demonstrate to create Hash object instance as shown. [ruby] Hash[[key =>|, value]* ] or Hash.new [or] Hash.new(obj) [or] Hash.new { |hash, key| block } [/ruby] Then user will get hash populated objects now by using the created object user can get any presented instance methods as shown in below code. [ruby] $, = ", " months = Hash.new( "month" ) months = {"1" => "January", "2" => "February"} keys = months.keys puts "#{keys}" [/ruby] Result By running the above code in command prompt, the output can be obtained as shown in the image below.

Summary

shape Key Points

  • To call method user need to have Hash object instances.
  • Hash is a data structure which stores items.
  • All key value pairs are embedded in curly braces.