Abhilash
Abhilash

Reputation: 2953

Create a new array with common string in all arrays in ruby

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.

Upvotes: 0

Views: 61

Answers (1)

Rajagopalan
Rajagopalan

Reputation: 6064

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(:&)

Upvotes: 4

Related Questions