Example output
Sure, here's an implementation of a binary search function in Ruby:
```ruby
def binary_search(arr, target)
low = 0
high = arr.length - 1
while low <= high
mid = (low + high) / 2
if arr[mid] == target
return mid
elsif arr[mid] < target
low = mid + 1
else
high = mid - 1
end
end
return -1
end
```
This function takes an array `arr` and a `target` value to search for, and returns the index of the target if it is found in the array, or `-1` if it is not found. It works by maintaining a `low` and `high` index, which define the portion of the array that is being searched. At each iteration of the loop, the function computes the `mid` index as the average of `low` and `high`, and then checks whether the target is at that index or whether it falls in the left or right half of the search range. It then adjusts the `low` and `high` indexes accordingly to narrow down the search range until the target is found or the search range is exhausted.
Here are some tests you can run to verify that the function works as expected:
```ruby
# Test 1: search for an element that is in the array
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target1 = 8
index1 = binary_search(arr1, target1)
puts "Test 1: Index of #{target1} in #{arr1} is #{index1} (expected: 7)"
# Test 2: search for an element that is not in the array
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target2 = 11
index2 = binary_search(arr2, target2)
puts "Test 2: Index of #{target2} in #{arr2} is #{index2} (expected: -1)"
# Test 3: search for an element in an empty array
arr3 = []
target3 = 5
index3 = binary_search(arr3, target3)
puts "Test 3: Index of #{target3} in #{arr3} is #{index3} (expected: -1)"
```
These tests cover three scenarios: searching for an element that is in the array, searching for an element that is not in the array, and searching for an element in an empty array. The tests print out the expected index and the actual index returned by the function, so you can verify that they match.