Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSabrina Robinson
3,167 PointsRuby version
Hey, I noticed there was no Ruby version of how to do the recursive example. I know that Python and Ruby are pretty similar and there are a few syntactic differences, but I was wondering if you would consider adding my example to your cheat sheet to help others that are more familiar with Ruby.
list = [1,2,3,4,5,6,7,8,9]
def binary_search_recursive(list, target)
return false if list.length == 0
first = 0
last = list.length - 1
mid_point = (list.length / 2).floor
if target == list[mid_point]
return true
else
if list[mid_point] < target
return binary_search_recursive(list[mid_point +1, last], target)
else
return binary_search_recursive(list[first, mid_point -1], target)
end
end
end
def verify(result)
puts "Target found: #{result}"
end
result = binary_search_recursive(list, 12)
verify(result)
result = binary_search_recursive(list, 6)
verify(result)
Also, I noticed this algorithm does not work for all the numbers in the list. Sometimes I get 'False' when I should get 'True', the numbers 1, 4, and 7 are examples of this. Let me know if I'm doing something wrong.