Categories
Programming

Arrays in Ruby

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.

2 replies on “Arrays in Ruby”

When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thank you!

Leave a Reply

OR LOG IN WITH




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