Skip to content

Instantly share code, notes, and snippets.

@eliotsykes
Created September 27, 2015 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliotsykes/ab4cf56e5768ec56b4dc to your computer and use it in GitHub Desktop.
Save eliotsykes/ab4cf56e5768ec56b4dc to your computer and use it in GitHub Desktop.
Ranges & Arrays
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