Hi is there a simple way to return true if at least one element of an
array matches at least one element of another array?
For example let’s say I have @groups = ‘4,6’.split(’,’) and @allowed =
‘1,4’.split(’,’)
I want these to be true because 4 is in both @groups and @allowed.
Thank you!
Hmm I came up with a very inelegant way to do this… that is:
@groups.length + @allowed.length > (@groups | @allowed).length
which is equivalent to 4 > 3 so it evaluates to true.
I guess this works but if you come up with a more elegant way please
share! Thanks.
Okay never mind just came up with a better way:
!(@groups & @allowed).empty?
=> true
Hello,
I want these to be true because 4 is in both @groups and @allowed.
You could check something like
sum = @groups+@allowed
if sum.uniq != sum
what_you_want_to_do_if_same_elements
end
Example:
a,b,c = [1,2],[2,3],[4,5]
=> [[1, 2], [2, 3], [4, 5]]
(a+b).uniq != (a+b)
=> true
(a+c).uniq != (a+c)
=> false
Cheers
“Kenneth Eunjung” [email protected] wrote in message
news:[email protected]…
Posted via http://www.ruby-forum.com/.
array1 & array2 returns a new_ array with elements common to
both arrays. Test on new_array.size returns true if common
elements exsist, false if not.
@groups = ‘4,6’.split(‘,’)
@allowed = ‘1,4’.split(‘,’)
a = @groups & @allowed # => [4]
puts a.inspect.to_s # => [4]
ret = (a.size > 0)
puts ret.to_s # => true
b = [4,6] & [5,7]
puts b.inspect.to_s # => []
ret = (b.size > 0)
puts ret.to_s # => false
exit
Hth gfb