Hash Maps in Ruby [Closed]

Hash Maps in Ruby [Closed]

Given:

hash = { "value" => 4, "details" => "I am some details"}, {"value" => 5, "details" => "I am new details"}

can I do something like:

hash.each do |key, value|
   puts "#{key} is #{value}"
end

to get something like:

{ "value" => 4, "details" => "I am some details"} is {"value" => 5, "details" => "I am new details"} is

If a hash table (map) is not what I want to do this with, what would be? Databases are out of the question. The user should be able to continue to add on to the end with another {} if they need to filling out the same details as what's in the first two.

1

3 Answers

You've created an array of hashes, which you can do more explicitly as:

hashes = [{:value => "foo"}, {:value => "bar"}]

You can then append with

hashes << {:value => "baz"}

If you're ever wondering what type of variable you're working with, you can do var.class:

hash = { "value" => 4, "details" => "I am some details"}, {"value" => 5, "details" => "I am new details"}
hash.class #=> Array

A Map is a mapping of Distinct Keys to Values; there are Map variations which relax this, but Ruby's Hashmap follows the standard Map ADT.

In this case an Array of two different Hashes (each with a "value" and a "details") is being created.

>  x = [1,2] # standard Array literal
   => [1,2]   
>  x = 1,2   # as in the posted code, no []'s, but ..
   => [1,2]  # .. the same: the =, production created the Array here!

So it's not a Hash in hash, but rather an Array (containing two Hash elements) :)

Compare the results with the following and note that b is nil each time:

["one","two","three","four"].each do |a,b|
    puts ">" + a + "|" + b
end

This is why it prints "hash1.to_str is hash2.to_str is" as the each iterates over the Array, as discussed above and only the first argument is populated with a meaningful value - one of the hashes.

I don't understand what "databases are out of the question" means in this context. Sounds like you're creating a data store, and so far it looks like you have a numeric ID with a related value.

A hash is a hash; you'd add values to the hash:

h = { "4" => "foo" } # Initial values
h["5"] = "ohai"
h["6"] = "kthxbai"
2
Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.