A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
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.
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.
No 'How to Implement the Solution' section available. Please consider contributing.
No 'How to Run the Solution' section available. Please consider contributing.