0

I'm trying to create a hash using an each loop as follows:

[
  hash = session[:cart].each do |product|
  price = product[0].price.to_i*100
  {
    name: product[0].name, description: product[0].description, quantity: product[1], amount: product[0].price
  }, #Is it possible to add a comma here? Doing this normally causes an error
  end
]

Which should hopefully produce this Output

Output

 [
   {name: "Hellow", description: "Many Hellows", quantity: 1, price: 1000},
   {name: "Hellow", description: "Many Hellows", quantity: 1, price: 1000}
 ]
4
  • In your hash, you wrote: "amount: price: product[0].price". Is that a typo? Commented Jul 21, 2014 at 19:22
  • And no. No need to put the comma at the end. Commented Jul 21, 2014 at 19:23
  • oh yes, that's a typo, let me correct it. i'm trying to use activemerchant and it seems to only accept the multiple hashes if there's a comma separating the hashes D: ... which is the point really since all of these will be in an array Commented Jul 21, 2014 at 19:26
  • Sorry for the unclear message again. Commented Jul 21, 2014 at 19:29

1 Answer 1

3

You want .map, not .each. Each iterates. Map translates one thing into another.

[
  session[:cart].map do |product|
    price = product[0].price.to_i*100
    {
      name: product[0].name,
      description: product[0].description,
      quantity: product[1],
      amount: product[0].price
    } 
  end
]
Sign up to request clarification or add additional context in comments.

6 Comments

Changing it to map seem to still seem to cause syntax error, unexpected ',', expecting keyword_end ... any ideas ? :O
@Kishe No comma. That comma after the last } has no meaning and is syntactically invalid.
Bonus Question: What if they need to be separated within an array as the edit above. (I'm really sorry i didn't mention this earlier)
@Kishe Then get rid of the hash = part, and wrap the whole thing in []. Please stop changing your question. If you have a new question, ask a new question, don't continually change the meaning of your old question.
@maegar Yessir. sorry about that.
|

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.