Ruby Arrays & Hashes

Arrays and hashes are Ruby's core data structures.

Arrays

Ruby
cities = ["Kathmandu", "Pokhara", "Chitwan"]
cities.push("Lalitpur")      # add to end
cities.pop                    # remove from end
cities.first                  # "Kathmandu"
cities.last                   # "Lalitpur"
cities.length                 # 4
cities.include?("Pokhara")    # true

Iterating

Ruby
numbers = [1, 2, 3, 4, 5]

numbers.each { |n| puts n }
numbers.each_with_index { |n, i| puts "#{i}: #{n}" }
doubled = numbers.map { |n| n * 2 }     # [2, 4, 6, 8, 10]
evens = numbers.select { |n| n.even? }   # [2, 4]
odds = numbers.reject { |n| n.even? }    # [1, 3, 5]
total = numbers.reduce(:+)                # 15

Hashes

Ruby
prices = {
  "Notebook" => 150,
  "Pen"      => 25,
  "Bag"      => 800,
}

prices["Pen"]           # 25
prices["Book"] = 200    # add new entry

# Symbol keys (shorthand)
prices = { notebook: 150, pen: 25 }
prices[:notebook]       # 150

Hash Methods

Ruby
prices.each { |item, price| puts "#{item}: #{price}" }
prices.keys              # [:notebook, :pen]
prices.values            # [150, 25]
prices.transform_values { |v| v * 1.13 }  # add 13% VAT

Ranges

Ruby
(1..5).to_a      # [1, 2, 3, 4, 5]
(1...5).to_a     # [1, 2, 3, 4]
("a".."f").to_a  # ["a", "b", "c", "d", "e", "f"]