【问题标题】:arrays comparison [duplicate]数组比较[重复]
【发布时间】:2012-01-23 09:07:37
【问题描述】:

可能重复:
How to count duplicates in Ruby Arrays
Ruby: Compare 2 arrays for matches, and count the number of match instances

我开始使用 ruby 语言。假设我有两个数组:

a=["A", "B", "C", "D"]
b=["C", "A", "X", "Y", "F"]

我想计算两个数组中重复元素的数量。为了实现这一点,我想出的想法如下:

nr_of_duplicates = (a- (a - b)).size

有没有更好的方法来实现这一点?

【问题讨论】:

标签: ruby


【解决方案1】:

在 Array 类中已经为此定义了一个名为“&”的方法:

ary & other_ary → new_ary

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

   [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多