funk-shun
funk-shun

Reputation: 4421

Dictionary = Hash?

Is a dictionary basically just a hash table?

Also bonus: In the Ruby code "Hash.new {0}" what is the "{0}" at the end for?

Upvotes: 19

Views: 21101

Answers (4)

sepp2k
sepp2k

Reputation: 370212

The words table, dictionary and map are often used synonymously (in the context of data structures). A hash table/hash map is one kind of table/dictionary/map.

The {0} is a block (anonymous function) which ignores its argument and returns the number 0. The block given to Hash.new is called to produce a default value when a key is not found in the hash map.

I.e. if I do h = Hash.new {0} and then h["key that does not exist"], I get back 0, instead of nil (which I'd get without the {0}). Note that in this case where the default value is immutable and does not depend on the key, you don't need to use the block form of Hash.new, you can just do Hash.new(0) to set 0 as the default value.

Upvotes: 32

Josh Bothun
Josh Bothun

Reputation: 1344

A dictionary is a conceptual interface. A hash table is a concrete implementation.

Upvotes: 4

geoffreyd
geoffreyd

Reputation: 1099

In Ruby a Hash is a key, value store

h = Hash.new
h['one'] = 1
h['one'] #=> 1
h['two'] #=> nil

the {0} is a block that will be evaluated if you where to call a Key that did not exist, it's like a default value.

h = Hash.new {0}
h['one'] #=> 0
h = Hash.new {|hash,key| "#{key} has Nothing"}
h['one'] #=> "one has Nothing"

Upvotes: 20

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272607

A dictionary just maps a key to a value. There are many ways to achieve this; a hash-table is one of them.

Upvotes: 7

Related Questions