在ruby中更好地替换join()和split()

时间:2014-10-16 14:02:43

标签: ruby arrays join

我有一系列字符串数组。

看起来像这样:

big_array = Array.new
big_array[0] = ["aib","ulster","anglo","hsbc"]
big_array[1] = ["ulster","hdfc","citibank"]
big_array[2] = ["aib", "citibank"]

现在,由此,我想创建另一个包含银行名称的数组。 我知道如何做到这一点的唯一方法是。

big_array.join(" ").split(" ").uniq

现在,这适用于少量数据。但是如果big_array的索引达到1000s那会怎么样呢。似乎不是最好的方法。有没有更好的方法来实现这个?

P.S。我刚刚给出了一个我想要做的例子。不是实际的代码。只是想要一个更优雅的解决方案。

2 个答案:

答案 0 :(得分:5)

您可以使用Array#flatten

big_array = Array.new
big_array[0] = ["aib","ulster","anglo","hsbc"]
big_array[1] = ["ulster","hdfc","citibank"]
big_array[2] = ["aib", "citibank"]
big_array.flatten.uniq
# => ["aib", "ulster", "anglo", "hsbc", "hdfc", "citibank"]

答案 1 :(得分:0)

或者更简洁:

big_array = []
big_array << ["aib","ulster","anglo","hsbc"]
big_array << ["ulster","hdfc","citibank"]
big_array << ["aib", "citibank"]
big_array.flatten.uniq