# Hash problem

Hi all,

I’m sure that there is somewhere an explanation on how this works but I
can’t find it by myself.

I need to have a hash like this one:

so I need a hash with hashes inside.

If I make

myhash.merge ({“name” => “Bail Organa”})

all I get it’s just the last pair, since it’s updating it everytime.

How can I have a hash like the first one?

I’m sure someone had this problem before.

Regards,
Antonio

Firstly hash notation is {“name” => “Admiral Ackbar”} and not
chance?)

To be honest it looks more like you need an Array of hashes.

data = Array.new
data << {“name” => “Admiral Ackbar”}
data << {“name” => “Bail Organa”}

puts data.inspect

Hi Peter
You have to do something like this:

hash = {}
hash[:name] = ‘Senyi’
array = []
array << hash
hash2 = {}
hash2[:name] = ‘Peter’
array << hash2

=> [{:name=>“Senyi”}, {:name=>“Peter”}]

I hope it helps you
Senyi

Antonio FernÃ¡ndez vara wrote:

I need to have a hash like this one:

Why a hash? If it only contains names, then why not

names = [“Admiral Ackbar”, “Bail Organa”]

Or so you want a hash with multiple values for one key:

myhash = Hash.new { |h,k| h[k] = [] }

myhash[“name”] << “Bail Organa”

Otherwise, as others have suggested, an array of hashes:

{“name”=>“Bail Organa”,“age”=>65}]

Or choose some attribute as a key, like id

2 => {“name”=>“Bail Organa”,“age”=>65}}

Le 01 septembre à 17:43, Peter H. a écrit :

data = Array.new
data << {“name” => “Admiral Ackbar”}
data << {“name” => “Bail Organa”}

C’mon, where’s the fun in that ?

require “ostruct”
=> true

a = []
=> []

a << OpenStruct.new(:name => “Admiral Ackbar”, :age => 30)

a << OpenStruct.new(:name => “Bail Organa”, :age => 65)
=> [#<OpenStruct name=“Admiral Ackbar”, age=30>, #<OpenStruct name=“Bail
Organa”, age=65>]

a[0].name