Insertion Sort in Ruby

Published on 14 May 2026 (Updated: 14 May 2026)

Welcome to the Insertion Sort in Ruby page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

# frozen_string_literal: true

class Array
  def insertion_sort!
    (1...length).each do |i|
      value = self[i]
      j = i - 1

      while j >= 0 && self[j] > value
        self[j + 1] = self[j]
        j -= 1
      end

      self[j + 1] = value
    end

    self
  end
end

def usage!
  abort %(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5")
end

def parse_input
  raw = ARGV.first
  usage! if raw.nil? || raw.strip.empty?

  numbers = raw.split(",").map { Integer(it.strip) }
  usage! if numbers.length < 2

  numbers
rescue ArgumentError
  usage!
end

puts parse_input.insertion_sort!.join(", ")

Insertion Sort in Ruby was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.