Ruby syntax for working with arrays (cheat-sheet):

symbol label what it does
, comma for indexing array by: index, length
.. two dots inclusive range
three dots non-inclusive range (doesn’t include last index)
+ plus concatenate two arrays
minus subtract two arrays
<< two less than append to end of array
& ampersand union of two arrays
| pipe intersection of two arrays

Some examples showing use of this:

Example Explanation What you get
[‘a’] << ['b','c'] append to end of array [‘a’,’b’,’c’]
[1,1,2,2,3] | [1,2,3,4] union of two arrays, duplicates are removed [1,2,3,4]
[1,2,3] & [2,3,4] intersection of two arrays [2,3]
a[0..-1] All but last element of array. (Note non-inclusive range … )
[1,2,3,4,5] basic syntax array [1,2,3]
[1…5] non-inclusive range [1,2,3,4]
a = [1..5] inclusive range [1,2,3,4,5]
a[0] the first element of the array 1
a[-1] another way to get the last element of the array 5
a[1,3] starting index & number of elements [2,3,4]
a = [1,2,3] + [4,5] concatenate two arrays [1,2,3,4,5]
[‘a’, ‘b’, ‘c’, ‘d’, ‘a’] – [‘b’, ‘c’] subtracts one array from another [‘a’, ‘d’]

Some more examples. Assume for each example that a = [“a”, “b”, “c”, “d”, “e”]

a[0…-1] All but last element of array. (Note non-inclusive range … )
a[0..-1] Everything in the array. (Note inclusive range .. )
a[1..-1] All but first element of array.

By Jason

Leave a Reply

Your email address will not be published. Required fields are marked *