Binary Search in Ruby

Published on 09 November 2024 (Updated: 07 May 2026)

Welcome to the Binary Search 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

module Enumerable
  def sorted?
    each_cons(2).all? { |a, b| (a <=> b) <= 0 }
  end
end

def parse_args
  list, key = ARGV
  raise ArgumentError unless list && key

  parts = list.split(",").map(&:strip)
  raise ArgumentError if parts.empty? || parts.any?(&:empty?)

  numbers = parts.map { Integer(it, exception: false) }
  raise ArgumentError if numbers.any?(nil)

  key = Integer(key, exception: false)
  raise ArgumentError if key.nil?

  raise ArgumentError unless numbers.sorted?

  [numbers, key]
end

begin
  numbers, key = parse_args
  puts !numbers.bsearch { key <=> it }.nil?
rescue ArgumentError
  warn 'Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")'
end

Binary Search 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.