How to initialize an array with a range of numbers in Ruby

1 Answer

0 votes
# Demonstrating several ways to build an array containing a range of numbers.
# Each function shows a different style that experienced developers commonly use.

# Build an array using Ruby's built‑in Range object.
# This is concise and uses the language's natural syntax.
def make_array_basic(start, end_exclusive)
  (start...end_exclusive).to_a
end

# Build an array using a manual loop.
# Clear and flexible; works well when adding extra logic.
def make_array_loop(start, end_exclusive)
  values = []
  start.upto(end_exclusive - 1) do |n|
    values << n
  end
  values
end

# Build an array using map on a range.
# Shows how to transform values while generating them.
def make_array_map(start, end_exclusive)
  (start...end_exclusive).map { |n| n }
end

# Build an array using Array.new with a block.
# Useful when generating values based on an index.
def make_array_new(start, end_exclusive)
  size = end_exclusive - start
  Array.new(size) { |i| start + i }
end

# Build an array using each_with_object.
# Demonstrates a functional style with an accumulator.
def make_array_each_with_object(start, end_exclusive)
  (start...end_exclusive).each_with_object([]) do |n, acc|
    acc << n
  end
end

# Print an array for demonstration.
def show(label, values)
  puts "#{label}: #{values.inspect}"
end

def main
  a = make_array_basic(1, 10)
  b = make_array_loop(1, 10)
  c = make_array_map(1, 10)
  d = make_array_new(1, 10)
  e = make_array_each_with_object(1, 10)

  show("basic range", a)
  show("loop", b)
  show("map", c)
  show("Array.new", d)
  show("each_with_object", e)
end

main


=begin
run:

basic range: [1, 2, 3, 4, 5, 6, 7, 8, 9]
loop: [1, 2, 3, 4, 5, 6, 7, 8, 9]
map: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array.new: [1, 2, 3, 4, 5, 6, 7, 8, 9]
each_with_object: [1, 2, 3, 4, 5, 6, 7, 8, 9]

=end

 



answered Aug 18 by avibootz
edited Aug 18 by avibootz
...