Creating, extending, traversing and combining Ruby arrays
Archive - Originally posted on "The Horse's Mouth" - 2010-09-30 06:50:30 - Graham EllisRuby shares many of its eclecticism's with Perl - lots of ways of doing the same thing, though it doesn't go quite so far (some would say so far beyond the reasonable) as Perl does. So when you come to create or manipulate an array (really an ordered list) there's a big choice.
indian = ["Refa","Melksham Tandoori","Broughton Balti"]
or
alternatives = %w(Lee's McDonalds Subway Grapes)
quite apart from a wide range of methods that will set up an array.
When you come to add something on to the end of an array, there's even more variety:
indian.push "Taj Mahal"
or
indian.push "The Palace on Wheels"
or
indian << "Sultan"
or
indian[6] = "Goa"
or
indian += ["Amritsar Star"]
or
indian[indian.length] = "The Curry House"
or
indian += alternatives
And when you come to iterate through it - well - have a look at the source of an example I've posted [here].
Once you've got a number of arrays, how can you combine them / manipulate them? Ruby's built in operators, running on array, can be used to and them (with &) and or them (with |) - allowing you to create a new array that contains only members that are common to both incoming arrays, or to create a new array that contains a members of both arrays combined, but eliminating the duplicate copy of members that appear in both. There's an example [here].