Thursday, May 17, 2012

What are arrays in ruby and how do they work?

Arrays are a built in data type in ruby, basically. You can define an array by typing something like a = [1,2,3], then you can get an element of the array with a[0], for instance. It's interesting to note that trying to say a[9] will NOT raise any sort of error, instead it will return a nil.


Just like in python, or any other mostly high-level language, arrays in ruby have a lot of built in methods. You can say [1,2,3] + [2,3,4], which will evaluate to [1,2,3,2,3,4], or you can do tricky things like intersection ([1,2,3] & [2,3,4] returns [2,3]) and union([1,2,3] | [2,3,4] returns [1,2,3,4]). Of course, array elements cannot only be integers, they can be whatever your heart desires.


There are as many or more built in methods for arrays as there are in python, and you can find them all at the documentation page for ruby arrays.


As for how they work, they are like arrays in any other language. They're an ordered sequence of objects, and the point is that you can access each one in constant time by providing its index. This is how they work.


So that's what arrays are, in ruby (and how they work). Or at least it's a start.

No comments:

Post a Comment