0

How would one write the following array in Ruby?

 $itemsarray = array();

 $itemsarray["items"]['0']['product_id'] = 1;
 $itemsarray["items"]['0']['brand_id'] = 1;
 $itemsarray["items"]['0']['color_id'] = 1;

 $itemsarray["items"]['1']['product_id'] = 2;
 $itemsarray["items"]['1']['brand_id'] = 3;
 $itemsarray["items"]['1']['color_id'] = 5;
0

2 Answers 2

2

It's very easy. Here is what you will need:

itemsarray = { 'items' => [ { 'product_id' => 1, 'brand_id' => 1, 'color_id' => 1 } ] }

Now a little bit of explanation...

In Ruby to represent an associative array we use Hashes. Ex.: { 'a' => 1, 'b' => 2 } == array('a' => 1, 'b' => 2).

So at the top level you have a hash containing the key items and it's value is an array of all the items. The first item is a hash again, having the product options as keys with their corresponding values.

What is a bit better way to write this is to use symbols instead of strings for the keys, as this will introduce a slight memory optimisation. Here is an example:

itemsarray = { :items => [ { :product_id => 1, :brand_id => 1, :color_id => 1 } ] }

There is also a shorthand syntax where :abc => 1 is equivalent to: abc: 1, so the above line would look like:

itemsarray = { items: [ { product_id: 1, brand_id: 1, color_id: 1 } ] }

UPDATE

With multiple items, here is how it would look like:

itemsarray = { items: [
                          { product_id: 1, brand_id: 1, color_id: 1 },
                          { product_id: 2, brand_id: 3, color_id: 5 }
                      ]}

Or a dynamic approach:

itemsarray[:items].push( { product_id: 2, brand_id: 3, color_id: 5 } )
Sign up to request clarification or add additional context in comments.

4 Comments

Great explanation, I knew this, however, I wanted to be able to add multiple 'items'. I changed the question a bit to reflect this.
Ah, the issue was syntactic. I was using the closing array bracket incorrectly. It's late here. ;)
@Jason Updated answer to reflect changes in the question
@Jason did you get this to work? looks like printaura api, i'm battling it over at stackoverflow.com/questions/46453190/… if you think you could help!
0
itemsarray={ items:[{product_id:1, brand_id:1, color_id:1} ]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.