RbRuby
BeginnerLesson 6 of 16

Arrays and Hashes – Ruby

The two most important collections and their most common pitfalls.

Arrays are ordered, mutable lists. << appends, negative indices count from the end, and with ranges you slice out parts. %w[...] is a shorthand for strings.

zahlen = [3, 1, 2]
zahlen << 5                # append
zahlen.sort!
puts zahlen.inspect        # [1, 2, 3, 5]
puts zahlen.first, zahlen.last, zahlen[-2]     # 1, 5, 3
puts zahlen[1..2].inspect  # [2, 3]
puts zahlen.include?(2), zahlen.size           # true, 4

wochentage = %w[Mo Di Mi]
puts wochentage.join(", ")
a, b, *rest = [1, 2, 3, 4]
puts rest.inspect          # [3, 4]

Hashes are key-value collections. Usually you use symbols (name:) as keys. With fetch you get a default value or an error instead of a silent nil, and dig reaches safely into nested structures.

person = { name: "Ada", alter: 36 }
person[:stadt] = "London"
puts person[:name]
puts person.fetch(:email, "none")       # none
person.each { |k, v| puts "#{k}: #{v}" }
puts person.keys.inspect, person.key?(:alter)

nested = { user: { profil: { stadt: "Bonn" } } }
puts nested.dig(:user, :profil, :stadt)  # Bonn

zaehler = Hash.new(0)
"hello world".each_char { |c| zaehler[c] += 1 unless c == " " }
puts zaehler["l"]                        # 3

Be careful with mutable default values: Hash.new([]) shares the same array for all keys. Use the block variant.

falsch = Hash.new([])
falsch[:a] << 1
puts falsch[:b].inspect     # [1]  – they all share the same array!

richtig = Hash.new { |h, k| h[k] = [] }
richtig[:a] << 1
puts richtig[:b].inspect    # []
TipSince Ruby 3.1 you may abbreviate when variables have the same name: x = 1; y = 2; punkt = { x:, y: }. Since Ruby 3.4, p displays a hash as {name: "Ada", "k" => 1} (formerly {:name=>"Ada"}).
Warningperson[:fehlt] returns nil – a common trigger for NoMethodError: undefined method for nil. Use fetch, dig or the safe navigation operator &..