Blocks, Procs, aur Lambdas
Ek block code ka ek chunk hai jo seedha ek method call se attached hota hai — either { |params| ... } ya is ke equivalent do |params| ... end. Ye koi value nahi hai; ye kisi variable ko assign nahi hota ya normal argument ki tarah pass nahi hota. Ek method wo block receive karta hai jo us ki call se attached tha aur usay yield se run karta hai, jo ek keyword hai, method nahi.
3.times { |i| puts "block: #{i}" }
def repeat(n)
n.times { |i| yield i }
end
repeat(3) { |i| puts "yielded: #{i}" }
block: 0 block: 1 block: 2 yielded: 0 yielded: 1 yielded: 2
repeat(3) { |i| ... } call ke sath ek block attach karta hai; repeat ke andar, yield i control ko us attached block ko hand karta hai, usay i pass karte hue. Ye Ruby ka khud ka mechanism hai — JavaScript ke (x) => x ya Python ke lambda x: x ki tarah ek lambda literal nahi jo ek anonymous function ko value ko assign karte hain. Ek tareeka hai block ko actual object mein badalne ka, though: Proc.new ek block ko value ki tarah capture karta hai, aur -> ("stabby lambda") same tareeke se bana ek lambda literal hai.
square = ->(x) { x * x }
cube = lambda { |x| x ** 3 }
adder = Proc.new { |x, y| x + y }
puts square.call(4)
puts cube.(3)
puts adder[2, 5]
16 27 7
.call, .(), aur [] Proc ya lambda ko invoke karne ke teen interchangeable tareeke hain — jab ek block is tarah object ki tarah capture ho jata hai, ye kisi bhi dusri value ki tarah behave karta hai: ye kisi variable mein store ho sakta hai, normal argument ki tarah pass ho sakta hai, aur jab chaho invoke ho sakta hai. Aage: Enumerable methods — map, select, aur reduce, ek sath chained, seedha blocks par build karte hue.
Practice exercise
def repeat(n) likho jo 0 se n-1 tak har index ko apne block mein yield kare. repeat(5) ko ek block ke sath call karo jo har i ko total mein add kare, phir total print karo.