Tutorial :Closures in Ruby



Question:

I'm having a little trouble with closures and I'd like to know what the equivalent code for the canonical make-adder procedure would be in Ruby.

In scheme it would be like:

(define (make-adder n)   (lambda (x) (+ x n))  


Solution:1

It's actually very close...

def make_addr n    lambda { |x| x + n }  end  t = make_addr 100  t.call 1  101  

In 1.9 you can use...

def make_addr n    ->(x) { x + n }  end  


Solution:2

One difference is that while Scheme has only one kind of procedure, Ruby has four. Most of the time, they behave similarly enough to your standard lambda, but you should try to understand all the details in depth.


Solution:3

Here's another way to do it in 1.9:

make_adder = -> n, x { n + x }  hundred_adder = make_adder.curry[100]  hundred_adder[4] # => 104  


Solution:4

Here is a pretty nice screen-cast explaining blocks and closures in Ruby: http://www.teachmetocode.com/screencasts/8


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »