Ruby: Hash Table (Key/Value List)

,

In Ruby, key/value list is just called hash.

#-*- coding: utf-8 -*-
# ruby

# define a keyed list
hh = {:john => 3, :mary => 4, :jane => 5, :vicky => 7}
p hh                   # ⇒ {:john=>3, :mary=>4, :jane=>5, :vicky=>7}

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

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

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

# get all keys
p hh.keys()                     # ⇒ [:john, :mary, :jane, :pretty]

# 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.

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.

blog comments powered by Disqus