简体   繁体   中英

How to push an array into a hash in ruby

I didn't find in the internet something that answers specifically my question.

I have a hash as follows:

hash = {[1111, 4, 20]}

And i want to push another array ( [3333, 2, 70] ) to that hash to get something like:

hash = {[1111, 4, 20], [3333, 2, 70]}

How can achieve this ?

Thanks!

What you're trying to have here is not a Hash. It's an Array of arrays. The syntax you wrote is not a valid Ruby syntax.

To add an item to an Array use << .

For example:

array = [[1111, 4, 20]]

To add an item you do:

array << [3333, 2, 70]

your array would be:

[[1111, 4, 20], [3333, 2, 70]]

It won't work. You probably want store those arrays in another array like this:

a = [[1111, 4, 20]]
a << [3333, 2, 70]
=> [[1111, 4, 20], [3333, 2, 70]]

Is that what you were looking for?

"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."

Please read more about ruby arrays and hashes: http://ruby-doc.org/core-2.2.0/Array.html http://ruby-doc.org/core-2.2.0/Hash.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM