tags:

views:

669

answers:

5
+1  Q: 

ruby hashes

Hello all,

I'd like to save some hash objects to a collection (in Java world think of List). I've search online to see if there is a similar data structure in ruby and have found none. For the moment being I've been trying to save hash a[] into hash b[], but have been having issues trying to get data out of hash b[].

Are there any built-in collection data structures on Ruby? If not, is saving a hash in another has common practice?

Thanks

A: 

Lists in Ruby are arrays. You can use Hash.to_a.

If you are trying to combine hash a with hash b, you can use Hash.merge

EDIT: If you are trying to insert hash a into hash b, you can do

b["Hash a"] = a;
CookieOfFortune
For clarification: merge will combine two hashes into one, not add one hash as a value into another hash.
Chuck
oh, I misunderstood what he wanted to do.
CookieOfFortune
Well, I'm not entirely certain which it is. I think it's a hash inside a hash, but I'm not sure.
Chuck
I was looking for a hash inside another hash, not hash combined with another hash. Thanks anyway.
rafael
+2  A: 

There shouldn't be any problem with that.

a = {:color => 'red', :thickness => 'not very'}
b = {:data => a, :reason => 'NA'}

Perhaps you could explain what problems you're encountering.

Chuck
+2  A: 

If it's accessing the hash in the hash that is the problem then try:

>> p = {:name => "Jonas", :pos => {:x=>100.23, :y=>40.04}}
=> {:pos=>{:y=>40.04, :x=>100.23}, :name=>"Jonas"}
>> p[:pos][:x]
=> 100.23
Jonas Elfström
+2  A: 

The question is not completely clear, but I think you want to have a list (array) of hashes, right?

In that case, you can just put them in one array, which is like a list in Java:

a = {:a => 1, :b => 2}
b = {:c => 3, :d => 4}
list = [a, b]

You can retrieve those hashes like list[0] and list[1]

Rutger Nijlunsing
A: 

All the answers here so far are about Hash in Hash, not Hash plus Hash, so for reasons of completeness, I'll chime in with this:

# Define two independent Hash objects
hash_a = { :a => 'apple', :b => 'bear', :c => 'camel' }
hash_b = { :c => 'car', :d => 'dolphin' }

# Combine two hashes with the Hash#merge method
hash_c = hash_a.merge(hash_b)

# The combined hash has all the keys from both sets
puts hash_c[:a] # => 'apple'
puts hash_c[:c] # => 'car', not 'camel' since B overwrites A

Note that when you merge B into A, any keys that A had that are in B are overwritten.

tadman