-2

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!

Rails Rails
  • 143
  • 1
  • 13
  • I can't really see how that's a hash. Where are the keys and the values? – Ahmed Fathy Sep 30 '15 at 19:56
  • The keys are implicit. I need them as I'm going to iterate using an `each` – Rails Rails Sep 30 '15 at 19:58
  • 1
    I think you just want nested arrays... `[[1111, 4, 20]] << [3333, 2, 70] # [[1111, 4, 20], [3333, 2, 70]]` – photoionized Sep 30 '15 at 20:00
  • *"I have a hash as follows: `hash = {[1111, 4, 20]}`"* - there's no such hash, that gives a syntax error. Please show your actual code. – Stefan Sep 30 '15 at 20:55
  • 1
    @RailsRails ok, let's say keys are implicit - at least implicit for us, the nebbish mortals :) but what about the second array? do you want to append this array to the implicit key's value array, or as any other explicit-but-implicit key's value? – marmeladze Sep 30 '15 at 21:39

2 Answers2

1

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]]
Ahmed Fathy
  • 529
  • 4
  • 20
1

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

grimsock
  • 774
  • 5
  • 18