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. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?