0

I am building up an array of products in rails. Which is working fine, but my question is...

Is there any way to update an item if it exists in the array already? So as I am looping through products, and the model is "TV-32D300B" I need to check the array to see if it exists, but it may only be a partial number like "TV-32D300" (minus the last letter).

If the is the case I want to be able to update that product with the correct details.

product = {
  name: product_name,
  url: product_url,
  modelnumber: product_modelnumber,
  category_id: category.id,
  group_id: category.group_id,
  image_url: image_url
}

I'm using the include? to add products to the array if a product doesn't already exist, so I am guessing I need to add a like condition to find the number.

unless products.include?(product)
  products << product
end
9
  • What if there are multiple items which match that number? Do you want to update each of them? Commented May 17, 2018 at 10:04
  • 1
    @Stefan I doubt I understand how is that possible. When the second one arises, it’s already been merged into the first one (assuming the order is valid and “submodels” come after “models,” or the check in my answer is tuned to find an intersection of strings.) Commented May 17, 2018 at 10:20
  • Basically, if the product TV-32D300B was to already exist, under TV-32D300 or TV-32D300B then that product should just update. It's unlikely that it would appear twice in a region. Commented May 17, 2018 at 10:30
  • Also, normally, the character B would change to say W but that would already be explicit. Then we could also fall back to check the colour that passed over Commented May 17, 2018 at 10:32
  • 2
    @mudasobwa not necessarily. You could add TV-32D300B, then TV-32D300W and finally have TV-32D300. Commented May 17, 2018 at 11:06

1 Answer 1

2

Assuming products is an array of hashes and what you call a model is a product_name held under name key in this hash, the following would do:

existing = products.find { |p| product[:name].include? p[:name] }
if existing
  # update existing
else
  products << product
end

More info on Enumerable#find.

Sign up to request clarification or add additional context in comments.

3 Comments

would this find the name if it's not an exact match?
Once String#include? is used, it would detect the first element in this array, that has a name that is included/contained in the product’s name, as you wanted the longer to match the shorter, not vice versa.
awesome, Thank you I will give that a try.

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.