Range Over Built in Ruby

Here we use range to sum the numbers in a slice. 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 map 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 map.

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 character and the second the character itself.

"go".each_char.with_index do |c, i|
  puts "#{i} #{c.ord}"
end

Run the Ruby script:

$ ruby range_over_built_in_types.rb
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111