Ruby: Hash Table

By Xah Lee. Date:

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.

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables