Dynamic programming using closures in Ruby

I was playing around with ruby and proc blocks caught my fancy. Here’s the code snippet (not a perfect algorithm, but shows the use of closures)

def get_angle_checker(start_angle, end_angle)
  return Proc.new { |angle| (start_angle <= angle  && angle < end_angle) }
end

acute_angle_checker = get_angle_checker(0, 90)
right_angle_checker = get_angle_checker(90, 91)
obtuse_angle_checker = get_angle_checker(91, 180)

puts acute_angle_checker.call(12)      #true
puts acute_angle_checker.call(90)      #false
puts right_angle_checker.call(90)      #true
puts obtuse_angle_checker.call(112)    #true

For some one looking for more info on closures, following resources may be useful:

http://martinfowler.com/bliki/Closure.html

http://blog.codahale.com/2005/11/24/a-ruby-howto-writing-a-method-that-uses-code-blocks/



One response to “Dynamic programming using closures in Ruby

  1. i wouldn’t have assumed this had been impressive several years in the past yet somehow its surprising just how years shifts the manner by which you experience individual concepts, thank you with regard to the article it is enjoyable to browse some thing clever occasionally instead of the standard crap mascarading as information sites on the internet, i’m going to enjoy a smattering of hands of facebook poker, adios for now

Leave a comment