Define_method with closures lets you create methods that remember values from their surrounding code. This helps make flexible and reusable methods.
0
0
Define_method with closures in Ruby
Introduction
When you want to create methods dynamically based on some data.
When you want methods to remember specific values without passing them every time.
When you want to avoid repeating similar methods with small differences.
When you want to keep related data and behavior together inside a method.
Syntax
Ruby
define_method(:method_name) do |parameters| # method body using parameters and closed-over variables end
define_method creates a method with the given name.
The block passed to define_method can use variables from outside its scope (closures).
Examples
This example defines a method
greet that remembers the instance variable @name using closure.Ruby
class Greeter def initialize(name) @name = name end define_method(:greet) do "Hello, #{@name}!" end end
This method
multiply remembers the @factor and multiplies it with the input number.Ruby
class Multiplier def initialize(factor) @factor = factor end define_method(:multiply) do |number| number * @factor end end
The
next method remembers and updates the @count variable each time it is called.Ruby
class Counter def initialize(start) @count = start end define_method(:next) do @count += 1 end end
Sample Program
This program creates a Person class. It defines a method say_hello using define_method that remembers the person's name and returns a greeting.
Ruby
class Person def initialize(name) @name = name end define_method(:say_hello) do "Hi, my name is #{@name}." end end person = Person.new("Alice") puts person.say_hello
OutputSuccess
Important Notes
Closures let the method remember variables like @name even after initialization.
Using define_method is useful for dynamic or repetitive method creation.
Be careful with variable scope to avoid unexpected results.
Summary
define_method creates methods dynamically with a block.
The block can use variables from outside, forming a closure.
This helps make flexible, reusable methods that remember data.