How to use closure in Ruby

5 Answers

0 votes
# A lambda that captures x and y from the surrounding scope.
x = 10
y = 20

add = -> { x + y }   # closure created here

result = add.call

puts result


=begin
run:

30

=end

 



answered 2 days ago by avibootz
0 votes
# Closures capture variables by reference

counter = 0

inc = -> { counter += 1 }  # closure captures counter

inc.call
inc.call

puts counter


=begin
run:

2

=end

 



answered 2 days ago by avibootz
0 votes
# Closures with parameters

factor = 3

multiply = ->(a, b) { (a + b) * factor }  # captures factor

puts multiply.call(5, 5)


=begin
run:

30

=end

 



answered 2 days ago by avibootz
0 votes
# Using a block as a closure

def apply_twice
  yield
  yield
end

x = 10

apply_twice { puts x }   # block captures x


=begin
run:

10
10

=end

 



answered 2 days ago by avibootz
0 votes
# Using Proc.new

x = 7

printer = Proc.new { puts x }  # captures x

printer.call


=begin
run:

7

=end

 



answered 2 days ago by avibootz

Related questions

4 answers 16 views
4 answers 23 views
4 answers 19 views
4 answers 20 views
3 answers 22 views
...