Wednesday, October 28, 2009

Finding Common Elements in Ruby Arrays

To find common elements in ruby arrays, use '|'. Eg.

%w{a b c d} | %w{c d e f}

# yields:

['c', 'd']


To find common elements in 2 dimensional array:

a1, a2, a3 = %w{a b c d}, %w{c d e f}, %w{d e f}
a = [a1, a2, a3]

a[1..-1].inject(a[0]) do |x, y|
x | y
end

# yields:

['d']


That's all !!

No comments:

Post a Comment

Labels