Ruby - Hash Hash Methods


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:


h1 = { 
    } # from   w ww  . ja  v  a  2s.c  o m
puts h1
h2 = {1=>'one', 2=>'two', 3=> 'three'} 
puts h2

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


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"]


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