0

I have an array with Product Ids and Color HEX Codes

Input:

@campaign.selectedproducts

Output:

["2,333333","1,333333",4,444444"] 

I'm trying to make a new array with all of the product data by finding it with id:

@selectedgifts = @campaign.selectedproducts.collect [{|i| Product.find(i) }, |i| i.split(',').last]

Array should output

["Product Object, HEX code", "Product Object, HEX code"]

¿Any help?

Thanks!

1
  • Is there a good reason why you can't use a different data shape? something like: { id: 2, color: "fff"} Commented Jul 14, 2022 at 13:47

2 Answers 2

1

You can try with group_by method like below:

@campaign.selectedproducts.group_by(&:color_code).transform_values{|val| val.pluck(:id).uniq}
Sign up to request clarification or add additional context in comments.

1 Comment

It appears "selectedproducts" is an Array of Strings, so I am not certain what color_code or pluck are in this instance.
0

Converting Product object to string is not what you want i guess. So i suggest you storing each element as hash instead of string.

@campaign.selectedproducts.map do |string|
  id, hex_code = string.split(',')
  product = Product.find(id)
  { product => hex_code }
end

Edit: Or you can store each element as array like this:

@campaign.selectedproducts.map do |string|
  id, hex_code = string.split(',')
  product = Product.find(id)
  [product, hex_code]
end

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.