Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a hash to an array?

Tags:

arrays

ruby

hash

I've currently got this hash:

{:residential=>"false"}

But I need to make it an item of an array:

[{:residential=>"false"}]

How do I do that?

like image 576
Shpigford Avatar asked Aug 30 '11 16:08

Shpigford


People also ask

Can you hash an array?

While an array can be used to construct hash tables, array indexes its elements using integers. However, if we want to store data and use keys other than integer, such as 'string', we may want to use dictionary. Dictionaries in Python are implemented using hash tables.

How do you push a hash array?

To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value. When inverted, you end up with a hash that has many values for the same key.

How do you hash an array in Ruby?

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

How do I assign an array to a hash in Perl?

To assign that array to a hash element, you'd use either $b{"x"} = [@a] or $b{"x"} = \@a , depending on what you're trying to do. [@a] makes a new arrayref containing a copy of the current contents of @a . If the contents of @a change after that, it has no effect on $b{x} .


2 Answers

my_array = []
my_array << {:residential => "false"}
=> [{:residential=>"false"}]
like image 130
mhoofman Avatar answered Oct 18 '22 22:10

mhoofman


The code you've already written should be just fine.

>> x = [{:residental=>"false"}, {:residental=>"true"}]                  
=> [{:residental=>"false"}, {:residental=>"true"}]                      
>> x[0][:residental]                                                    
=> "false"
like image 40
Mitch Lindgren Avatar answered Oct 18 '22 22:10

Mitch Lindgren