当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Array intersection用法及代码示例


Array#&()是一个Array类方法,它对数组执行集合相交操作。并返回两个数组的共同点。

用法:Array.&()

参数:用于执行相交操作的数组。


返回:两个数组中的公共元素。

范例1:

# Ruby code for &() method 
# showing intersection operation 
   
# declaration of array 
a = [18, 22, 33, 4, 5, 6] 
   
# declaration of array 
b = [5, 4, 22, 1, 88, 9] 
   
# declaration of array 
c = [18, 22, 33, 40, 50, 6] 
   
# a intersecting b 
puts "intersection of a and b:#{a & b}\n\n"
   
# a intersecting c 
puts "intersection of a and c:#{a & c}\n\n"
   
# b intersecting c 
puts "intersection of b and c:#{b & c}\n\n"

输出:

intersection of a and b:[22, 4, 5]

intersection of a and c:[18, 22, 33, 6]

intersection of b and c:[22]

范例2:

# Ruby code for &() method 
# showing intersection operation 
   
# declaration of array 
a = ["abc", "xyz", "dog"] 
   
# declaration of array 
b = ["cow", "cat", "dog"] 
   
# declaration of array 
c = ["cat", "1", "dog"] 
   
# a intersecting b 
puts "intersection of a and b:#{a & b}\n\n"
   
# a intersecting c 
puts "intersection of a and c:#{a & c}\n\n"
   
# b intersecting c 
puts "intersection of b and c:#{b & c}\n\n"

输出:

intersection of a and b:["dog"]

intersection of a and c:["dog"]

intersection of b and c:["cat", "dog"]


相关用法


注:本文由纯净天空筛选整理自mayank5326大神的英文原创作品 Ruby | Array intersection operation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。