Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures in Ruby

Tags:

closures

ruby

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))
like image 705
burlsm Avatar asked Nov 28 '09 06:11

burlsm


1 Answers

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
like image 179
DigitalRoss Avatar answered Sep 20 '22 16:09

DigitalRoss