How to Initialize an Array Inside a Hash in Ruby

How can I initialize an Array inside a Hash in Ruby

@my_hash = Hash.new(Array.new)

This creates exactly one array object, which is returned every time a key is not found. Since you only ever mutate that array and never create a new one, all your keys map to the same array.

What you want to do is:

@my_hash = Hash.new {|h,k| h[k] = Array.new }

or simply

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

Passing a block to Hash.new differs from simply passing an argument in 2 ways:

  1. The block is executed every time a key is not found. Thus you'll get a new array each time. In the version with an argument, that argument is evaluated once (before new is called) and the result of that is returned every time.

  2. By doing h[k] = you actually insert the key into the hash. If you don't do this just accessing @my_hash[some_key] won't actually cause some_key to be inserted in the hash.

add or insert to array inside a hash

Normally I'd attack it like this:

checks = data['checks'] ||= [ ]
checks << DateTime.now

If your data hash will only ever have array-like values, do this:

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

Then you don't need to bother with the ||= thing since assignment will happen automatically.

How to access an array element inside a hash in Ruby

Here's one way to access the second value of the first key of your hash:

cities.values.first[1]
# => -87.61184692382812

This fetches the value of your first key (in this case it's that first array in the hash), and then retrieves by index the second element of that array.

Creating a Hash with values as arrays and default value as empty array

Lakshmi is right. When you created the Hash using Hash.new([]), you created one array object.

Hence, the same array is returned for every missing key in the Hash.

That is why, if the shared array is edited, the change is reflected across all the missing keys.

Using:

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

Creates and assigns a new array for each missing key in the Hash, so that it is a unique object.

Creating array of hashes in ruby

Assuming what you mean by "rowofrows" is an array of arrays, heres a solution to what I think you're trying to accomplish:

array_of_arrays = [["abc",9898989898,"abc@xyz.com"], ["def",9898989898,"def@xyz.com"]]

array_of_hashes = []
array_of_arrays.each { |record| array_of_hashes << {'name' => record[0], 'number' => record[1].to_i, 'email' => record[2]} }

p array_of_hashes

Will output your array of hashes:

[{"name"=>"abc", "number"=>9898989898, "email"=>"abc@xyz.com"}, {"name"=>"def", "number"=>9898989898, "email"=>"def@xyz.com"}]

How to initialize a hash with keys from an array?

Here we go using Enumerable#each_with_object and Hash::[].

 keys = [ 'a' , 'b' , 'c' ]
Hash[keys.each_with_object(nil).to_a]
# => {"a"=>nil, "b"=>nil, "c"=>nil}

or Using Array#product

keys = [ 'a' , 'b' , 'c' ]
Hash[keys.product([nil])]
# => {"a"=>nil, "b"=>nil, "c"=>nil}

Ruby access hash within an array within a hash (and add new hash)

You can return values for specific key (:a)

data[:a]
# => [{:label=>"Person", :title=>"Manager", :name=>"Mike Waldo"}, {:label=>"Person", :title=>"Developer", :name=>"Jeff Smith"}]

And if you need to save value to :a Hash so you just use

data[:a] << {:label => "new label", :name => "new name", :titles => "new title"}
# => [{:label=>"Person", :title=>"Manager", :name=>"Mike Waldo"}, {:label=>"Person", :title=>"Developer", :name=>"Jeff Smith"}, {:label=>"new label", :name=>"new name", :titles=>"new title"}]

btw: your command (data.each{|x, y| puts y[0][:name]}) just return name value for fist hash if you need all names for all hashe you can use

data.each do |k, a|
a.each do |h|
puts h[:name]
end
end

HOW-TO Create an Array of Hashes in Ruby

You're using a Symbol as the index into the Hash object that uses String objects as keys, so simply do this:

@collection = array[0]["firstname"]

I would encourage you to use Symbols as Hash keys rather than Strings because Symbols are cached, and therefore more efficient, so this would be a better solution:

def collection
hash = { :firstname => "Mark", :lastname => "Martin", :age => 24, :gender => "M" }
array = []
array.push(hash)
@collection = array[0][:firstname]
end


Related Topics



Leave a reply



Submit