1

In the following array, how would I find the position of the product with id = 71?

[[[#<Product id: 71>, #<BigDecimal:x>], 0], [[#<Product id: 73>, #<BigDecimal:x>], 1]]

Alternatively, if I have @product = Product.find(71), how would I then find that this object is associated with the number 0 and not 1 in the above array?

1 Answer 1

4

You can use Array#index with block, with block arguments deconstruction (here using symbols instead of your custom objects):

arr = [[[:a, :b], 5], [[:c, :d], 7]]
# => [[[:a, :b], 5], [[:c, :d], 7]] 
arr.index{|((a, b), c)| c == 7}
# => 1 
arr.index{|((a, b), c)| b == :a}
# => nil 
arr.index{|((a, b), c)| b == :b}
# => 0 

If you are interested in particular element, rather than its index, just use find instead of index (block argument would be the same).

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

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.