Ruby: Hash Table

By Xah Lee. Date: . Last updated: .

In Ruby, Hash Map is a ordered list of key/value pairs. (in Ruby since v1.9 (year 2009), its hashmap is ordered.) Tip: in other programing languages, it's called dictionary, or association list, or keyed list, or map.

# ruby

# define a hash table
hh = {:john => 3, :mary => 4, :joe => 5, :vicky => 7}
p hh == {:john=>3, :mary=>4, :joe=>5, :vicky=>7}

# getting value from a key
p hh[:mary] == 4

# add a entry
hh[:jenny] = 99
p hh == {:john=>3, :mary=>4, :joe=>5, :vicky=>7, :jenny=>99}

# delete a entry
hh.delete :vicky
p hh == {:john=>3, :mary=>4, :joe=>5, :jenny=>99}

# get all keys
p hh.keys() == [:john, :mary, :joe, :jenny]

# get all values
p hh.values() == [3, 4, 5, 99]

# check if a key exists
p (hh.has_key?(:mary)) == true
p (hh.has_value?(:jenny)) == false

In Ruby, :something is a “symbol”. It's similar to lisp's symbol. For practical purposes, you can think of it as a static string. Whenever you need to use a string as a label, you should use symbol instead.

In the above example, you could replace all symbols by string. But using symbol is more efficient, because each string is a full object

In Ruby, “everything” is a object. So, creating a string creates a object, which often means it's slow. So, the “symbol” datatype is a solution for that.

# ruby

# hash, with keys as string
aa = {"john" => 3, "mary" => 4, "joe" => 5}

# hash, with keys as symbol.
bb = {:john => 3, :mary => 4, :joe => 5}

In Ruby, “everything” is a object. So, creating a string creates a object, which often means it's slow. So, the “symbol” datatype is a solution for that.