Skip to content

Instantly share code, notes, and snippets.

@stevecass
Last active August 29, 2015 14:10
Show Gist options
  • Save stevecass/1b6fddec67f9233939c2 to your computer and use it in GitHub Desktop.
Save stevecass/1b6fddec67f9233939c2 to your computer and use it in GitHub Desktop.
Ruby array recap
arr = [] # => []
arr = Array.new # => []
arr = Array.new(5, "t") # => ["t", "t", "t", "t", "t"]
arr = Array.new(5) { |i| i **2 } # => [0, 1, 4, 9, 16]
arr[3] = 'replacement' # => "replacement"
arr # => [0, 1, 4, "replacement", 16]
arr.fetch 0 # => 0
arr.first # => 0
arr.last # => 16
arr.each { |ele| p ele} # => [0, 1, 4, "replacement", 16]
# Output:
# >> 0
# >> 1
# >> 4
# >> "replacement"
# >> 16
arr.push 'item' # => [0, 1, 4, "replacement", 16, "item"]
arr.pop # => "item"
arr.unshift 'another' # => ["another", 0, 1, 4, "replacement", 16]
arr.shift # => "another"
arr # => [0, 1, 4, "replacement", 16]
arr[0] = '4' # => "4"
arr.delete('4') # => "4"
arr.delete('not_there') # => nil
arr.delete_at(3) # => 16
arr # => [1, 4, "replacement"]
#Note that delete operates in-place. It returns the item deleted not a copy of the resulting array
arr=[0,1,2,3,4,5,6] # => [0, 1, 2, 3, 4, 5, 6]
arr.drop(3) # => [3, 4, 5, 6]
# i.e. the return value is the array without the first three elements
arr # => [0, 1, 2, 3, 4, 5, 6]
# but the original array is unaffected
# So delete is in-place but drop returns a copy of the array with the items dropped
arr=[0,1,2,3,4,5,6] # => [0, 1, 2, 3, 4, 5, 6]
arr.drop_while { |ele| ele < 5} # => [5, 6]
arr.select { |ele| ele > 4} # => [5, 6]
arr.map { |ele| ele * 2} # => [0, 2, 4, 6, 8, 10, 12]
arr.reduce(:+) # => 21
arr.reduce(2, :+) # => 23
arr.reduce { |sum, ele| sum + ele } # => 21
arr.reduce(20) { |sum, ele| sum + ele } # => 41
#Note that inject may also be used in place of reduce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment