Created
September 27, 2015 15:21
-
-
Save eliotsykes/ab4cf56e5768ec56b4dc to your computer and use it in GitHub Desktop.
Ranges & Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fruits = ['apples', 'bananas', 'coconuts', 'dates', 'elderberry'] | |
# Array[ ] accepts an integer to lookup by index, this is what we | |
# do most of the time when we work with arrays: | |
fruits[0] #=> 'apples' | |
fruits[2] #=> 'coconuts' | |
fruits[4] #=> 'elderberry' | |
# Array[ ] accepts negative integers too. These get special treatment. They | |
# count backwards from the end of the array: | |
fruits[-1] #=> 'elderberry' | |
fruits[-3] #=> 'coconuts' | |
fruits[-5] #=> 'apples' | |
# Array[ ] accepts Ranges too. These return all of the elements | |
# from the array with an index covered by the Range: | |
fruits[0..-1] #=> ['apples', 'bananas', 'coconuts', 'dates', 'elderberry'] | |
fruits[0..4] #=> ['apples', 'bananas', 'coconuts', 'dates', 'elderberry'] | |
fruits[2..4] #=> ['coconuts', 'dates', 'elderberry'] | |
# Print all the numbers in a Range. | |
(2..5).to_a.each { |i| puts i } # prints 2, 3, 4, 5 each on a new line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment