Range Over Built in Crystal

Range iterates over elements in a variety of built-in data structures. Let’s see how to use range with some of the data structures we’ve already learned.

# Here we use `range` to sum the numbers in an array. Arrays work like this too.
nums = [2, 3, 4]
sum = 0
nums.each do |num|
  sum += num
end
puts "sum: #{sum}"

# `range` on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.
nums.each_with_index do |num, i|
  if num == 3
    puts "index: #{i}"
  end
end

# `range` on hash iterates over key/value pairs.
kvs = {"a" => "apple", "b" => "banana"}
kvs.each do |k, v|
  puts "#{k} -> #{v}"
end

# `range` can also iterate over just the keys of a hash.
kvs.each_key do |k|
  puts "key: #{k}"
end

# `range` on strings iterates over Unicode code points. The first value is the starting byte index of the rune and the second the rune itself.
"go".each_char_with_index do |c, i|
  puts "#{i} #{c.ord}"
end

To run the program, save the code in a file with a .cr extension and use the Crystal compiler.

$ crystal run your_file.cr
sum: 9
index: 1
a → apple
b → banana
key: a
key: b
0 103
1 111

Next example: Pointers.