MC logo

Hashes

  Ruby Example Code

<<Arrays hash1.rb Line Breaking>>
z = { 'mike' => 75, 'bill' => 18, 'alice' => 32 }
z['joe'] = 44
print z['bill'], " ", z['joe'], " ", z["smith"], "\n"
print z.has_key?('mike'), " ", z.has_key?("jones"), "\n"

See:Ruby User's Guide

Ruby hashes are similar to maps or dictionaries in other languages. They are essentially arrays whose subscripts are not limited to integer values. You can create them with the curly-bracked list notation shown, but you can also assign to a subscript expression to add members. It's not at all unreasonable to create a hash with empty brackets, then add members using subscripting.

Method names may end in ?, hence the name of the has_key? method. This suggests a the method is a test which returns a boolean value. Such methods are sometimes known as predicates.
<<Arrays Line Breaking>>