Ruby Arrays and Hashes

Working with arrays and hash collections

Arrays

arr = [1, 2, 3] # create array
empty = Array.new # empty array
arr[0] # access first element
arr.first # first element
arr.last # last element
arr.length # get length

Array Methods

arr.push(4) # add to end
arr << 5 # add to end (shorthand)
arr.pop # remove from end
arr.unshift(0) # add to beginning
arr.shift # remove from beginning
arr.delete(2) # remove specific value
arr.include?(3) # check if contains

Array Iteration

arr.each { |x| puts x } # iterate elements
arr.map { |x| x * 2 } # transform elements
arr.select { |x| x > 2 } # filter elements
arr.reject { |x| x < 2 } # exclude elements
arr.reduce(0) { |sum, x| sum + x } # reduce to single value

Hashes

hash = { "name" => "John", "age" => 30 } # create hash
hash = { name: "John", age: 30 } # symbol keys syntax
hash[:name] # access value
hash[:city] = "NYC" # add key-value pair

Hash Methods

hash.keys # get all keys
hash.values # get all values
hash.has_key?(:name) # check if key exists
hash.delete(:age) # remove key
hash.each { |key, val| puts "#{key}: #{val}" } # iterate