Ruby - Hash Hash Methods

Introduction

Hash class has built-in methods.

To delete an item from a hash using its key, use the delete method:

aHash.delete( someKey )

To test if a key or value exists, use the has_key? and has_value?

methods:aHash.has_key?( someKey ) 
aHash.has_value?( someValue ) 

To combine two hashes, use the merge method:

hash1.merge( hash2 ). 

To return a new hash created using the original hash's values as keys and its keys as values, use aHash.invert.

To return an array populated with the hash's keys or values, use aHash.keys and aHash.values.

Here's an example that uses some of these methods:

Demo

h1 = { 
    'room1'=>'A', 
    'room2'=>'B', 
    'loc1'=>'C', 
    'loc2'=>'D'  
    } #   w  w  w . j a v  a 2 s . c  om
puts h1
                         
h2 = {1=>'one', 2=>'two', 3=> 'three'} 
puts h2

h1['room1'] = 'You have wandered into a dark room' 

h1.delete('loc2') 
p(h1) 

p(h1.has_key?('loc2'))  #=> false 
p(h2.has_value?("two")) #=>true 
p(h2.invert)            #=> {"one"=>1, "two"=>2, "three"=>3} 
p(h2.keys)              #=>[1, 2, 3] 
p(h2.values)            #=>["one", "two", "three"]

Result

To find the position of an item in a hash, use the index method with Ruby 1.8 and the key method in Ruby 1.9.

The index method is still present in Ruby 1.9 but is deprecated:

h2.index("two")    # use this with Ruby 1.8 
h2.key("two")          # use this Ruby 1.9