0

Lets say we have below array

arrays=[["a","b", "c"],["b","g","c"],["b","c","g"]]

To find common array fields we can do arrays[0] & arrays[1] & arrays[2] which will return ["b","c"] in this case. This works fine. But how can we do the same when the array count is not predictable?

My initial thought is doing something like a loop like this.

array_count.times do |index|
 #but this way how can I achieve same above or any better approach???
end

Thank you.

5
  • 2
    Your question is a bit unclear. What do you mean by dynamically? Commented May 26, 2018 at 6:26
  • @mbuechmann Just meant the array count is not static. so need looping Commented May 26, 2018 at 6:29
  • Why are you mentioning arrays[3]? Commented May 28, 2018 at 3:40
  • Your result cannot be reproduced. Commented May 28, 2018 at 3:40
  • 1
    @sawa Thank you for reporting. It was a mistake and haven't noticed when I wrote the question as I put that just to provide a basic idea on the requirement. fixed it now though.. Commented May 29, 2018 at 6:10

1 Answer 1

4

Use Reduce method

result=arrays.reduce do |x,y|
  x & y
end

p result

output

["b", "c"]

Update

Another short way would be

 arrays.reduce(:&)
Sign up to request clarification or add additional context in comments.

4 Comments

Or arrays.reduce(:&).
@mu is too short ah okay, updated your short solution.
I have a general suggestion. If someone leaves a comment that contains what you regard as an improvement on your answer, don't just include it as an addendum to your question, but instead rewrite your answer. Here you might begin with @muistooshort's suggestion and possibly then--for the benefit of those new to Ruby--explain what that means when used with a block instead. You can then thank the commenter in a comment, saying you have altered your answer in light of the suggestion. After all, the whole idea is to make answers as educational as possible.
@Cary Swoveland sure , I will do henceforth.

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.