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:

{“name”:“Admiral Ackbar”},{“name”:“Bail Organa”}

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.

Thanks in advance.


Firstly hash notation is {“name” => “Admiral Ackbar”} and not
{“name”:“Admiral Ackbar”} (are you thinking about PHP or Python by

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
=> [{“name”=>“Admiral Ackbar”}, {“name”=>“Bail Organa”}]

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

Antonio Fernández vara wrote:

I need to have a hash like this one:

{“name”:“Admiral Ackbar”},{“name”:“Bail Organa”}

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:
{“name”=>[“Admiral Ackbar”,“Bail Organa”]}

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

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

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

[{“name”=>“Admiral Ackbar”,“age”=>30},
{“name”=>“Bail Organa”,“age”=>65}]

Or choose some attribute as a key, like id

{ 1 => {“name”=>“Admiral Ackbar”,“age”=>30},
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 ? :slight_smile:

require “ostruct”
=> true

a = []
=> []

a << OpenStruct.new(:name => “Admiral Ackbar”, :age => 30)
=> [#<OpenStruct 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>]

=> “Admiral Ackbar”

=> 65

a.find { |e| e.age > 50 }
=> #<OpenStruct name=“Bail Organa”, age=65>