Pindub_Amateur Pindub_Amateur - 2 months ago 27
Ruby Question

Better alternative to join() and split() in ruby

I have an array of arrays of Strings.

It looks like this:

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


Now, from this, I want to create another array with the names of the banks.
The only way I know how to do this is.

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


Now, this works for small amounts of data. But what if big_array's indexes run up to 1000s. Doesn't seem like the best way to do this. Is there a better way to implement this?

P.S. I've just given an example for what I'm trying to do. Not the actual code. Just want a more elegant solution.

Answer

You can use 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"]