Complete the code to create a closure that returns a lambda adding a fixed number.
def make_adder(n) return ->(x) { x [1] n } end add_five = make_adder(5) puts add_five.call(10)
The lambda adds the fixed number n to the argument x. So the operator must be +.
Complete the code to capture the variable correctly inside the closure.
def make_multipliers multipliers = [] 3.times do |i| multipliers << ->(x) { x * [1] } end multipliers end procs = make_multipliers puts procs[0].call(2)
The variable i is captured by the lambda to multiply x by i. This shows variable binding in closures.
Fix the error in the closure to correctly capture the loop variable value.
def make_procs procs = [] 3.times do |i| val = i procs << -> { val [1] 1 } end procs end procs = make_procs puts procs[1].call
The lambda adds 1 to the captured val. Using + fixes the closure to use the correct value.
Fill both blanks to create a closure that captures the current loop variable and multiplies it.
def make_funcs funcs = [] 4.times do |i| funcs << ->(x) { (x [1] i) [2] 2 } end funcs end funcs = make_funcs puts funcs[2].call(3)
The closure adds i to x and then raises the result to the power of 2 using **.
Fill all three blanks to create a closure that filters and transforms a hash based on variable binding.
def filter_transform(data) result = data.select { |k, v| v [1] 10 } .map { |k, v| [k.[2], v [3] 5] } result.to_h end input = {"a" => 12, "b" => 8, "c" => 15} output = filter_transform(input) puts output
The code selects key-value pairs where the value is greater than 10, then transforms keys to uppercase and subtracts 5 from values.