Closures in Ruby
Ruby supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
To run the program, save it as closures.rb
and use the ruby
command:
In Ruby, closures are typically implemented using Proc objects or lambda functions. The ->
syntax used in this example is a shorthand for creating a lambda.
The int_seq
method returns a new Proc each time it’s called. This Proc maintains its own state (the value of i
), which persists between calls to the Proc.
When we call next_int
multiple times, we see the value incrementing, demonstrating that the Proc is maintaining its state. When we create a new Proc with new_ints = int_seq
, it starts with its own fresh state, separate from next_int
.
This example showcases how closures in Ruby can be used to create function factories, each producing a function with its own encapsulated state.