2

I'd like to save some hash objects to a collection (in the Java world think of it as a List). I 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 hash common practice?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Rafael
  • 1,061
  • 4
  • 16
  • 32

5 Answers5

3

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
  • 30,834
  • 6
  • 70
  • 106
2

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
  • 234,037
  • 30
  • 302
  • 389
2

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
  • 4,861
  • 1
  • 21
  • 24
1

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
  • 13,836
  • 8
  • 42
  • 58
1

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
  • 208,517
  • 23
  • 234
  • 262