Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I want to create a Hash in Ruby with default values as an empty array

So, I coded

x = Hash.new([])

However, when I try to push a value into it

x[0].push(99)

All the keys get 99 pushed into that array. How do I resolve this?

like image 947
Ninjinx Avatar asked May 21 '15 07:05

Ninjinx


People also ask

How do you turn an array into a hash?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

What is a ruby hash?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

What characterizes a hash?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.


2 Answers

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.

like image 72
Myst Avatar answered Oct 23 '22 19:10

Myst


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

h[0].push(99)

This will result in {0=>[99]}


When Hash.new([]) is used, a single object is used as the default value (i.e. value to be returned when a hash key h[0] does not return anything), in this case one array.

So when we say h[0].push(99), it pushes 99 into that array but does not assign h[0] anything. So if you output h you will still see an empty hash {}, while the default object will be [99].


Whereas, when a block is provided i.e. Hash.new{|h,k| h[k] = [] } a new object is created and is assigned to h[k] every time a default value is required.

h[0].push(99) will assign h[0] = [] and push value into this new array.

like image 20
Lakshmi Avatar answered Oct 23 '22 18:10

Lakshmi