Arrays

10.1 Creating Arrays

nums = [1, 2, 3]
words = %w[apple banana cherry]        # array of strings
syms = %i[a b c]
empty = []
zeros = Array.new(5, 0)                # [0, 0, 0, 0, 0]
squares = Array.new(5) { |i| i * i }   # [0, 1, 4, 9, 16]
Array(nil); Array([1]); Array(1..3)    # safe conversion
grid = Array.new(3) { Array.new(3, 0) }   # (don't use Array.new(3, []): it shares one object!)

10.2 Accessing and Modifying

a = [10, 20, 30, 40, 50]
a[0]; a[-1]; a[1..3]; a[1, 2]; a.first; a.first(2); a.last(2)
a.fetch(10, "default"); a.dig(0); a.values_at(0, 2)
a.sample; a.shuffle
a << 60; a.push(70, 80); a.unshift(0); a.insert(2, 15)
a.pop; a.shift; a.delete(15); a.delete_at(0); a.delete_if { |x| x > 60 }
a.concat([90, 100]); a + [1]; a - [10]; a & [20, 30]; a | [1]
a.compact; a.flatten; a.uniq; a.reverse; a.rotate; a.clear
a.include?(20); a.index(20); a.count(20); a.empty?; a.length
a.slice!(0, 2); a.fill(0); a.replace([1, 2])

10.3 Transforming and Querying

nums = [5, 3, 8, 1, 9, 2]
nums.sort; nums.sort.reverse; nums.sort { |a, b| b <=> a }; nums.max(2); nums.min_by { |n| -n }
nums.sum; nums.minmax; nums.take(3); nums.drop(3); nums.take_while { |n| n > 2 }
nums.each_slice(2).to_a           # [[5, 3], [8, 1], [9, 2]]
nums.each_cons(2).to_a            # sliding window
nums.zip(%w[a b c d e f])
nums.partition(&:even?)           # [[8, 2], [5, 3, 1, 9]]
nums.group_by(&:odd?)
nums.tally                        # counts occurrences
[[1, 2], [3, 4]].to_h             # {1=>2, 3=>4}
[[1, 2], [3, 4]].transpose
[1, [2, [3, [4]]]].flatten(1)
[3, 1, 2].sort!                   # in place (bang)
nums.join(", ")
nums.combination(2).to_a; nums.permutation(2).first(3); [1, 2].product([3, 4])
nums.each_with_index { |n, i| puts "#{i}: #{n}" }
nums.cycle.first(10)
nums.bsearch { |x| x >= 4 }       # binary search on a sorted array
nums.pack("C*")                   # binary packing
nums.sum { |n| n * 2 }
nums.filter_map { |n| n * 2 if n.odd? }   # select + map in one pass

10.4 Destructuring and Splat

first, second, *others = [1, 2, 3, 4, 5]
def coords = [3, 4]
x, y = coords
combined = [*1..3, *[4, 5]]       # [1, 2, 3, 4, 5]